Skip to main content
.NET Framework Class Library
StringWriter Class

Implements a TextWriter for writing information to a string. The information is stored in an underlying StringBuilder.

Namespace:   System.IO
Assemblies:   mscorlib (in mscorlib.dll)
  System.IO (in System.IO.dll)
Syntax
<[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_0_0_0%]> _
<[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_0_0_1%](True)> _
Public Class StringWriter _
	Inherits [%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_0_0_2%]
[[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_1_0_0%]]
[[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_1_0_1%](true)]
public class StringWriter : [%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_1_0_2%]
[[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_2_0_0%]]
[[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_2_0_1%](true)]
public ref class StringWriter : public [%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_2_0_2%]
[<[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_3_0_0%]>]
[<[%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_3_0_1%](true)>]
type StringWriter =  
    class 
        inherit [%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_3_0_2%] 
    end
public class StringWriter extends [%$TOPIC/hs9kt2e9_en-us_VS_110_4_0_4_0_0%]

The StringWriter type exposes the following members.

Constructors
  NameDescription
Public method Supported by the XNA Framework Supported by Portable Class Library StringWriterInitializes a new instance of the StringWriter class.
Public method Supported by the XNA Framework Supported by Portable Class Library StringWriter(IFormatProvider)Initializes a new instance of the StringWriter class with the specified format control.
Public method Supported by the XNA Framework Supported by Portable Class Library StringWriter(StringBuilder)Initializes a new instance of the StringWriter class that writes to the specified StringBuilder.
Public method Supported by the XNA Framework Supported by Portable Class Library StringWriter(StringBuilder, IFormatProvider)Initializes a new instance of the StringWriter class that writes to the specified StringBuilder and has the specified format provider.
Top
Properties
  NameDescription
Public property Supported by the XNA Framework Supported by Portable Class Library EncodingGets the Encoding in which the output is written. (Overrides TextWriterEncoding.)
Public property Supported by the XNA Framework Supported by Portable Class Library FormatProviderGets an object that controls formatting. (Inherited from TextWriter.)
Public property Supported by the XNA Framework Supported by Portable Class Library NewLineGets or sets the line terminator string used by the current TextWriter. (Inherited from TextWriter.)
Top
Methods
  NameDescription
Public method Supported by the XNA Framework CloseCloses the current StringWriter and the underlying stream. (Overrides TextWriterClose.)
Public method CreateObjRefCreates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework Supported by Portable Class Library DisposeReleases all resources used by the TextWriter object. (Inherited from TextWriter.)
Protected method Supported by the XNA Framework Supported by Portable Class Library Dispose(Boolean)Releases the unmanaged resources used by the StringWriter and optionally releases the managed resources. (Overrides TextWriterDispose(Boolean).)
Public method Supported by the XNA Framework Supported by Portable Class Library Equals(Object)Determines whether the specified object is equal to the current object. (Inherited from Object.)
Protected method Supported by the XNA Framework Supported by Portable Class Library FinalizeAllows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection. (Inherited from Object.)
Public method Supported by the XNA Framework Supported by Portable Class Library FlushClears all buffers for the current writer and causes any buffered data to be written to the underlying device. (Inherited from TextWriter.)
Public method FlushAsyncAsynchronously clears all buffers for the current writer and causes any buffered data to be written to the underlying device. (Overrides TextWriterFlushAsync.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetHashCodeServes as the default hash function. (Inherited from Object.)
Public method GetLifetimeServiceRetrieves the current lifetime service object that controls the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework Supported by Portable Class Library GetStringBuilderReturns the underlying StringBuilder.
Public method Supported by the XNA Framework Supported by Portable Class Library GetTypeGets the Type of the current instance. (Inherited from Object.)
Public method InitializeLifetimeServiceObtains a lifetime service object to control the lifetime policy for this instance. (Inherited from MarshalByRefObject.)
Protected method Supported by the XNA Framework Supported by Portable Class Library MemberwiseCloneCreates a shallow copy of the current Object. (Inherited from Object.)
Protected method MemberwiseClone(Boolean)Creates a shallow copy of the current MarshalByRefObject object. (Inherited from MarshalByRefObject.)
Public method Supported by the XNA Framework Supported by Portable Class Library ToStringReturns a string containing the characters written to the current StringWriter so far. (Overrides ObjectToString.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Boolean)Writes the text representation of a Boolean value to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Char)Writes a character to the string. (Overrides TextWriterWrite(Char).)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Char)Writes a character array to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Decimal)Writes the text representation of a decimal value to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Double)Writes the text representation of an 8-byte floating-point value to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Int32)Writes the text representation of a 4-byte signed integer to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Int64)Writes the text representation of an 8-byte signed integer to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Object)Writes the text representation of an object to the text string or stream by calling the ToString method on that object. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Single)Writes the text representation of a 4-byte floating-point value to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(String)Writes a string to the current string. (Overrides TextWriterWrite(String).)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(UInt32)Writes the text representation of a 4-byte unsigned integer to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(UInt64)Writes the text representation of an 8-byte unsigned integer to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Write(String, Object)Writes a formatted string to the text string or stream, using the same semantics as the StringFormat(String, Object) method. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(String, Object)Writes a formatted string to the text string or stream, using the same semantics as the StringFormat(String, Object) method. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library Write(Char, Int32, Int32)Writes a subarray of characters to the string. (Overrides TextWriterWrite(Char, Int32, Int32).)
Public method Supported by the XNA Framework Write(String, Object, Object)Writes a formatted string to the text string or stream, using the same semantics as the StringFormat(String, Object, Object) method. (Inherited from TextWriter.)
Public method Write(String, Object, Object, Object)Writes a formatted string to the text string or stream, using the same semantics as the StringFormat(String, Object, Object, Object) method. (Inherited from TextWriter.)
Public method WriteAsync(Char)Writes a character to the string asynchronously. (Overrides TextWriterWriteAsync(Char).)
Public method WriteAsync(Char)Writes a character array to the text string or stream asynchronously. (Inherited from TextWriter.)
Public method WriteAsync(String)Writes a string to the current string asynchronously. (Overrides TextWriterWriteAsync(String).)
Public method WriteAsync(Char, Int32, Int32)Writes a subarray of characters to the string asynchronously. (Overrides TextWriterWriteAsync(Char, Int32, Int32).)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLineWrites a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Boolean)Writes the text representation of a Boolean value followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Char)Writes a character followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Char)Writes an array of characters followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Decimal)Writes the text representation of a decimal value followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Double)Writes the text representation of a 8-byte floating-point value followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Int32)Writes the text representation of a 4-byte signed integer followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Int64)Writes the text representation of an 8-byte signed integer followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Object)Writes the text representation of an object by calling the ToString method on that object, followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Single)Writes the text representation of a 4-byte floating-point value followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(String)Writes a string followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(UInt32)Writes the text representation of a 4-byte unsigned integer followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(UInt64)Writes the text representation of an 8-byte unsigned integer followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework WriteLine(String, Object)Writes a formatted string and a new line to the text string or stream, using the same semantics as the StringFormat(String, Object) method. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(String, Object)Writes out a formatted string and a new line, using the same semantics as Format. (Inherited from TextWriter.)
Public method Supported by the XNA Framework Supported by Portable Class Library WriteLine(Char, Int32, Int32)Writes a subarray of characters followed by a line terminator to the text string or stream. (Inherited from TextWriter.)
Public method Supported by the XNA Framework WriteLine(String, Object, Object)Writes a formatted string and a new line to the text string or stream, using the same semantics as the StringFormat(String, Object, Object) method. (Inherited from TextWriter.)
Public method WriteLine(String, Object, Object, Object)Writes out a formatted string and a new line, using the same semantics as Format. (Inherited from TextWriter.)
Public method WriteLineAsyncWrites a line terminator asynchronously to the text string or stream. (Inherited from TextWriter.)
Public method WriteLineAsync(Char)Writes a character followed by a line terminator asynchronously to the string. (Overrides TextWriterWriteLineAsync(Char).)
Public method WriteLineAsync(Char)Writes an array of characters followed by a line terminator asynchronously to the text string or stream. (Inherited from TextWriter.)
Public method WriteLineAsync(String)Writes a string followed by a line terminator asynchronously to the current string. (Overrides TextWriterWriteLineAsync(String).)
Public method WriteLineAsync(Char, Int32, Int32)Writes a subarray of characters followed by a line terminator asynchronously to the string. (Overrides TextWriterWriteLineAsync(Char, Int32, Int32).)
Top
Fields
  NameDescription
Protected field Supported by the XNA Framework Supported by Portable Class Library CoreNewLineStores the newline characters used for this TextWriter. (Inherited from TextWriter.)
Top
Remarks

StringWriter enables you to write to a string synchronously or asynchronously. You can write a character at a time with the Write(Char) or the WriteAsync(Char) method, a string at a time using the Write(String) or the WriteAsync(String) method. In addition, you can write a character, an array of characters or a string followed by the line terminator asynchronously with one of the WriteLineAsync methods.

Important noteImportant

This type implements the IDisposable interface. When you have finished using the type, you should dispose of it either directly or indirectly. To dispose of the type directly, call its Dispose method in a try /catch block. To dispose of it indirectly, use a language construct such as using (in C#) or Using (in Visual Basic). For more information, see the “Using an Object that Implements IDisposable” section in the IDisposable interface topic.

The following table lists examples of other typical or related I/O tasks.

To do this...

See the example in this topic...

Create a text file.

How to: Write Text to a File

Write to a text file.

How to: Write Text to a File

Read from a text file.

How to: Read Text from a File

Append text to a file.

How to: Open and Append to a Log File

FileAppendText

FileInfoAppendText

Get the size of a file.

FileInfoLength

Get the attributes of a file.

FileGetAttributes

Set the attributes of a file.

FileSetAttributes

Determine if a file exists.

FileExists

Read from a binary file.

How to: Read and Write to a Newly Created Data File

Write to a binary file.

How to: Read and Write to a Newly Created Data File

Examples

The following code example demonstrates the creation of a continuous paragraph from a group of double-spaced sentences, and then the conversion of the paragraph back to the original text.

Option Explicit
Option Strict

Imports Microsoft.VisualBasic
Imports System
Imports System.IO

Public Class StrReader

    Shared Sub Main()

        Dim textReaderText As String = "TextReader is the " & _
            "abstract base class of StreamReader and " & _
            "StringReader, which read characters from streams " & _
            "and strings, respectively." & _
            vbCrLf & vbCrLf & _
            "Create an instance of TextReader to open a text " & _
            "file for reading a specified range of characters, " & _
            "or to create a reader based on an existing stream." & _
            vbCrLf & vbCrLf & _
            "You can also use an instance of TextReader to read " & _
            "text from a custom backing store using the same " & _
            "APIs you would use for a string or a stream." & _
            vbCrLf & vbCrLf

        Console.WriteLine("Original text:" & vbCrLf & vbCrLf & _
            textReaderText)

        ' From textReaderText, create a continuous paragraph  
        ' with two spaces between each sentence. 
        Dim aLine, aParagraph As String 
        Dim strReader As New StringReader(textReaderText)
        While True
            aLine = strReader.ReadLine()
            If aLine Is Nothing Then
                aParagraph = aParagraph & vbCrLf
                Exit While 
            Else
                aParagraph = aParagraph & aLine & " " 
            End If 
        End While
        Console.WriteLine("Modified text:" & vbCrLf & vbCrLf & _ 
            aParagraph)

        ' Re-create textReaderText from aParagraph. 
        Dim intCharacter As Integer  
        Dim convertedCharacter As Char  
        Dim strWriter As New StringWriter()
        strReader = New StringReader(aParagraph)
        While True
            intCharacter = strReader.Read()

            ' Check for the end of the string  
            ' before converting to a character. 
            If intCharacter = -1 Then 
                Exit While 
            End If

            convertedCharacter = Convert.ToChar(intCharacter)
            If convertedCharacter = "."C Then
                strWriter.Write("." & vbCrLf & vbCrLf)

                ' Bypass the spaces between sentences.
                strReader.Read()
                strReader.Read()
            Else
                strWriter.Write(convertedCharacter)
            End If 
        End While
        Console.WriteLine(vbCrLf & "Original text:" & vbCrLf & _ 
            vbCrLf & strWriter.ToString())

    End Sub 
End Class
using System;
using System.IO;

class StringRW
{
    static void Main()
    {
        string textReaderText = "TextReader is the abstract base " +
            "class of StreamReader and StringReader, which read " +
            "characters from streams and strings, respectively.\n\n" +

            "Create an instance of TextReader to open a text file " +
            "for reading a specified range of characters, or to " +
            "create a reader based on an existing stream.\n\n" +

            "You can also use an instance of TextReader to read " +
            "text from a custom backing store using the same " +
            "APIs you would use for a string or a stream.\n\n";

        Console.WriteLine("Original text:\n\n{0}", textReaderText);

        // From textReaderText, create a continuous paragraph  
        // with two spaces between each sentence. 
        string aLine, aParagraph = null;
        StringReader strReader = new StringReader(textReaderText);
        while(true)
        {
            aLine = strReader.ReadLine();
            if(aLine != null)
            {
                aParagraph = aParagraph + aLine + " ";
            }
            else
            {
                aParagraph = aParagraph + "\n";
                break;
            }
        }
        Console.WriteLine("Modified text:\n\n{0}", aParagraph);

        // Re-create textReaderText from aParagraph. 
        int intCharacter;
        char convertedCharacter;
        StringWriter strWriter = new StringWriter();
        strReader = new StringReader(aParagraph);
        while(true)
        {
            intCharacter = strReader.Read();

            // Check for the end of the string  
            // before converting to a character. 
            if(intCharacter == -1) break;

            convertedCharacter = Convert.ToChar(intCharacter);
            if(convertedCharacter == '.')
            {
                strWriter.Write(".\n\n");

                // Bypass the spaces between sentences.
                strReader.Read();
                strReader.Read();
            }
            else
            {
                strWriter.Write(convertedCharacter);
            }
        }
        Console.WriteLine("\nOriginal text:\n\n{0}", 
            strWriter.ToString());
    }
}
using namespace System;
using namespace System::IO;
int main()
{
   String^ textReaderText = "TextReader is the abstract base " 
   "class of StreamReader and StringReader, which read " 
   "characters from streams and strings, respectively.\n\n" 
   "Create an instance of TextReader to open a text file " 
   "for reading a specified range of characters, or to " 
   "create a reader based on an existing stream.\n\n" 
   "You can also use an instance of TextReader to read " 
   "text from a custom backing store using the same " 
   "APIs you would use for a string or a stream.\n\n";
   Console::WriteLine(  "Original text:\n\n{0}", textReaderText );

   // From textReaderText, create a continuous paragraph  
   // with two spaces between each sentence.
      String^ aLine;
   String^ aParagraph;
   StringReader^ strReader = gcnew StringReader( textReaderText );
   while ( true )
   {
      aLine = strReader->ReadLine();
      if ( aLine != nullptr )
      {
         aParagraph = String::Concat( aParagraph, aLine,  " " );
      }
      else
      {
         aParagraph = String::Concat( aParagraph,  "\n" );
         break;
      }
   }

   Console::WriteLine(  "Modified text:\n\n{0}", aParagraph );

   // Re-create textReaderText from aParagraph. 
   int intCharacter;
   Char convertedCharacter;
   StringWriter^ strWriter = gcnew StringWriter;
   strReader = gcnew StringReader( aParagraph );
   while ( true )
   {
      intCharacter = strReader->Read();

      // Check for the end of the string  
      // before converting to a character. 
      if ( intCharacter == -1 )
            break;


      convertedCharacter = Convert::ToChar( intCharacter );
      if ( convertedCharacter == '.' )
      {
         strWriter->Write(  ".\n\n" );

         // Bypass the spaces between sentences.
         strReader->Read();
         strReader->Read();
      }
      else
      {
         strWriter->Write( convertedCharacter );
      }
   }

   Console::WriteLine(  "\nOriginal text:\n\n{0}", strWriter->ToString() );
}
Version Information

.NET Framework

Supported in: 4.6, 4.5, 4, 3.5, 3.0, 2.0, 1.1

.NET Framework Client Profile

Supported in: 4, 3.5 SP1

XNA Framework

Supported in: 3.0, 2.0, 1.0

Portable Class Library

Supported in: Portable Class Library

Supported in: Windows Phone 8.1

Supported in: Windows Phone Silverlight 8.1

Supported in: Windows Phone Silverlight 8
Thread Safety
Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.