Skip to main content
StringWriter Class
 

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

Namespace:   System.IO
Assembly:  mscorlib (in mscorlib.dll)

SystemObject
   SystemMarshalByRefObject
     System.IOTextWriter
      System.IOStringWriter

[SerializableAttribute]
[ComVisibleAttribute(true)]
public class StringWriter : TextWriter
[SerializableAttribute]
[ComVisibleAttribute(true)]
public ref class StringWriter : TextWriter
[<SerializableAttribute>]
[<ComVisibleAttribute(true)>]
type StringWriter = 
    class
        inherit TextWriter
    end
<SerializableAttribute>
<ComVisibleAttribute(True)>
Public Class StringWriter
	Inherits TextWriter
NameDescription
System_CAPS_pubmethod StringWriter

Initializes a new instance of the StringWriter class.

System_CAPS_pubmethod StringWriter

Initializes a new instance of the StringWriter class with the specified format control.

System_CAPS_pubmethod StringWriter

Initializes a new instance of the StringWriter class that writes to the specified StringBuilder.

System_CAPS_pubmethod StringWriter

Initializes a new instance of the StringWriter class that writes to the specified StringBuilder and has the specified format provider.

NameDescription
System_CAPS_pubproperty

Gets the Encoding in which the output is written.(Overrides .)

System_CAPS_pubproperty

Gets an object that controls formatting.(Inherited from TextWriter.)

System_CAPS_pubproperty

Gets or sets the line terminator string used by the current TextWriter.(Inherited from TextWriter.)

NameDescription
System_CAPS_pubmethod Close

Closes the current StringWriter and the underlying stream.(Overrides TextWriterClose.)

System_CAPS_pubmethod CreateObjRef

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethod Dispose

Releases all resources used by the TextWriter object.(Inherited from TextWriter.)

System_CAPS_protmethod Dispose

Releases the unmanaged resources used by the StringWriter and optionally releases the managed resources.(Overrides TextWriterDispose.)

System_CAPS_pubmethod Equals

Determines whether the specified object is equal to the current object.(Inherited from Object.)

System_CAPS_protmethod Finalize

Allows an object to try to free resources and perform other cleanup operations before it is reclaimed by garbage collection.(Inherited from Object.)

System_CAPS_pubmethod Flush

Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.(Inherited from TextWriter.)

System_CAPS_pubmethod FlushAsync

Asynchronously clears all buffers for the current writer and causes any buffered data to be written to the underlying device. (Overrides TextWriterFlushAsync.)

System_CAPS_pubmethod GetHashCode

Serves as the default hash function. (Inherited from Object.)

System_CAPS_pubmethod GetLifetimeService

Retrieves the current lifetime service object that controls the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethod GetStringBuilder

Returns the underlying StringBuilder.

System_CAPS_pubmethod GetType

Gets the Type of the current instance.(Inherited from Object.)

System_CAPS_pubmethod InitializeLifetimeService

Obtains a lifetime service object to control the lifetime policy for this instance.(Inherited from MarshalByRefObject.)

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current Object.(Inherited from Object.)

System_CAPS_protmethod MemberwiseClone

Creates a shallow copy of the current MarshalByRefObject object.(Inherited from MarshalByRefObject.)

System_CAPS_pubmethod ToString

Returns a string containing the characters written to the current StringWriter so far.(Overrides ObjectToString.)

System_CAPS_pubmethod Write

Writes the text representation of a Boolean value to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a character to the string.(Overrides TextWriterWrite.)

System_CAPS_pubmethod Write

Writes a character array to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a subarray of characters to the string.(Overrides TextWriterWrite.)

System_CAPS_pubmethod Write

Writes the text representation of a decimal value to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of an 8-byte floating-point value to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of a 4-byte signed integer to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of an 8-byte signed integer to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of an object to the text string or stream by calling the ToString method on that object.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of a 4-byte floating-point value to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a string to the current string.(Overrides TextWriterWrite.)

System_CAPS_pubmethod Write

Writes a formatted string to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a formatted string to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a formatted string to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes a formatted string to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of a 4-byte unsigned integer to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod Write

Writes the text representation of an 8-byte unsigned integer to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteAsync

Writes a character to the string asynchronously.(Overrides TextWriterWriteAsync.)

System_CAPS_pubmethod WriteAsync

Writes a character array to the text string or stream asynchronously.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteAsync

Writes a subarray of characters to the string asynchronously.(Overrides TextWriterWriteAsync.)

System_CAPS_pubmethod WriteAsync

Writes a string to the current string asynchronously.(Overrides TextWriterWriteAsync.)

System_CAPS_pubmethod WriteLine

Writes a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes the text representation of a Boolean value followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes a character followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes an array of characters followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes a subarray of characters followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes the text representation of a decimal value followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

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.)

System_CAPS_pubmethod WriteLine

Writes the text representation of a 4-byte signed integer followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes the text representation of an 8-byte signed integer followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

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.)

System_CAPS_pubmethod WriteLine

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.)

System_CAPS_pubmethod WriteLine

Writes a string followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes a formatted string and a new line to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes a formatted string and a new line to the text string or stream, using the same semantics as the StringFormat method.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes out a formatted string and a new line, using the same semantics as Format.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes out a formatted string and a new line, using the same semantics as Format.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes the text representation of a 4-byte unsigned integer followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLine

Writes the text representation of an 8-byte unsigned integer followed by a line terminator to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLineAsync

Writes a line terminator asynchronously to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLineAsync

Writes a character followed by a line terminator asynchronously to the string.(Overrides TextWriterWriteLineAsync.)

System_CAPS_pubmethod WriteLineAsync

Writes an array of characters followed by a line terminator asynchronously to the text string or stream.(Inherited from TextWriter.)

System_CAPS_pubmethod WriteLineAsync

Writes a subarray of characters followed by a line terminator asynchronously to the string.(Overrides TextWriterWriteLineAsync.)

System_CAPS_pubmethod WriteLineAsync

Writes a string followed by a line terminator asynchronously to the current string.(Overrides TextWriterWriteLineAsync.)

NameDescription
System_CAPS_protfield CoreNewLine

Stores the newline characters used for this TextWriter.(Inherited from TextWriter.)

StringWriter enables you to write to a string synchronously or asynchronously. You can write a character at a time with the Write or the WriteAsync method, a string at a time using the Write or the WriteAsync 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.

System_CAPS_importantImportant

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.

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

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.

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());
    }
}
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 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() );
}
Universal Windows Platform
Available since 8
.NET Framework
Available since 1.1
Portable Class Library
Supported in: portable .NET platforms
Silverlight
Available since 2.0
Windows Phone Silverlight
Available since 7.0
Windows Phone
Available since 8.1

Any public static (Shared in Visual Basic) members of this type are thread safe. Any instance members are not guaranteed to be thread safe.

Return to top