StringWriter StringWriter StringWriter StringWriter Class

Definition

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

public ref class StringWriter : System::IO::TextWriter
[System.Runtime.InteropServices.ComVisible(true)]
public class StringWriter : System.IO.TextWriter
type StringWriter = class
    inherit TextWriter
Public Class StringWriter
Inherits TextWriter
Inheritance
Attributes

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.

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() );
}

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

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.

Note

This type implements the IDisposable interface, but does not actually have any resources to dispose. This means that disposing it by directly calling Dispose() or by using a language construct such as using (in C#) or Using (in Visual Basic) is not necessary.

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

File.AppendText

FileInfo.AppendText
Get the size of a file. FileInfo.Length
Get the attributes of a file. File.GetAttributes
Set the attributes of a file. File.SetAttributes
Determine if a file exists. File.Exists
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

Constructors

StringWriter() StringWriter() StringWriter() StringWriter()

Initializes a new instance of the StringWriter class.

StringWriter(IFormatProvider) StringWriter(IFormatProvider) StringWriter(IFormatProvider) StringWriter(IFormatProvider)

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

StringWriter(StringBuilder) StringWriter(StringBuilder) StringWriter(StringBuilder) StringWriter(StringBuilder)

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

StringWriter(StringBuilder, IFormatProvider) StringWriter(StringBuilder, IFormatProvider) StringWriter(StringBuilder, IFormatProvider) StringWriter(StringBuilder, IFormatProvider)

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

Properties

Encoding Encoding Encoding Encoding

Gets the Encoding in which the output is written.

FormatProvider FormatProvider FormatProvider FormatProvider

Gets an object that controls formatting.

(Inherited from TextWriter)
NewLine NewLine NewLine NewLine

Gets or sets the line terminator string used by the current TextWriter.

(Inherited from TextWriter)

Methods

Close() Close() Close() Close()

Closes the current StringWriter and the underlying stream.

CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type) CreateObjRef(Type)

Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(Inherited from MarshalByRefObject)
Dispose() Dispose() Dispose() Dispose()

Releases all resources used by the TextWriter object.

(Inherited from TextWriter)
Dispose(Boolean) Dispose(Boolean) Dispose(Boolean) Dispose(Boolean)

Releases the unmanaged resources used by the StringWriter and optionally releases the managed resources.

Equals(Object) Equals(Object) Equals(Object) Equals(Object)

Determines whether the specified object is equal to the current object.

(Inherited from Object)
Flush() Flush() Flush() Flush()

Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.

(Inherited from TextWriter)
FlushAsync() FlushAsync() FlushAsync() FlushAsync()

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

GetHashCode() GetHashCode() GetHashCode() GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService() GetLifetimeService() GetLifetimeService() GetLifetimeService()

Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
GetStringBuilder() GetStringBuilder() GetStringBuilder() GetStringBuilder()

Returns the underlying StringBuilder.

GetType() GetType() GetType() GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService() InitializeLifetimeService()

Obtains a lifetime service object to control the lifetime policy for this instance.

(Inherited from MarshalByRefObject)
MemberwiseClone() MemberwiseClone() MemberwiseClone() MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean) MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString() ToString() ToString() ToString()

Returns a string containing the characters written to the current StringWriter so far.

Write(Boolean) Write(Boolean) Write(Boolean) Write(Boolean)

Writes the text representation of a Boolean value to the text string or stream.

(Inherited from TextWriter)
Write(Char) Write(Char) Write(Char) Write(Char)

Writes a character to the string.

Write(Char[]) Write(Char[]) Write(Char[]) Write(Char[])

Writes a character array to the text string or stream.

(Inherited from TextWriter)
Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32) Write(Char[], Int32, Int32)

Writes a subarray of characters to the string.

Write(Decimal) Write(Decimal) Write(Decimal) Write(Decimal)

Writes the text representation of a decimal value to the text string or stream.

(Inherited from TextWriter)
Write(Double) Write(Double) Write(Double) Write(Double)

Writes the text representation of an 8-byte floating-point value to the text string or stream.

(Inherited from TextWriter)
Write(Int32) Write(Int32) Write(Int32) Write(Int32)

Writes the text representation of a 4-byte signed integer to the text string or stream.

(Inherited from TextWriter)
Write(Int64) Write(Int64) Write(Int64) Write(Int64)

Writes the text representation of an 8-byte signed integer to the text string or stream.

(Inherited from TextWriter)
Write(Object) Write(Object) Write(Object) 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)
Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>) Write(ReadOnlySpan<Char>)
Write(Single) Write(Single) Write(Single) Write(Single)

Writes the text representation of a 4-byte floating-point value to the text string or stream.

(Inherited from TextWriter)
Write(String) Write(String) Write(String) Write(String)

Writes a string to the current string.

Write(String, Object) Write(String, Object) Write(String, Object) Write(String, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object) method.

(Inherited from TextWriter)
Write(String, Object, Object) Write(String, Object, Object) Write(String, Object, Object) Write(String, Object, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object, Object) method.

(Inherited from TextWriter)
Write(String, Object, Object, Object) Write(String, Object, Object, Object) Write(String, Object, Object, Object) Write(String, Object, Object, Object)

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object, Object, Object) method.

(Inherited from TextWriter)
Write(String, Object[]) Write(String, Object[]) Write(String, Object[]) Write(String, Object[])

Writes a formatted string to the text string or stream, using the same semantics as the Format(String, Object[]) method.

(Inherited from TextWriter)
Write(UInt32) Write(UInt32) Write(UInt32) Write(UInt32)

Writes the text representation of a 4-byte unsigned integer to the text string or stream.

(Inherited from TextWriter)
Write(UInt64) Write(UInt64) Write(UInt64) Write(UInt64)

Writes the text representation of an 8-byte unsigned integer to the text string or stream.

(Inherited from TextWriter)
WriteAsync(Char) WriteAsync(Char) WriteAsync(Char) WriteAsync(Char)

Writes a character to the string asynchronously.

WriteAsync(Char[]) WriteAsync(Char[]) WriteAsync(Char[]) WriteAsync(Char[])

Writes a character array to the text string or stream asynchronously.

(Inherited from TextWriter)
WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32) WriteAsync(Char[], Int32, Int32)

Writes a subarray of characters to the string asynchronously.

WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken) WriteAsync(ReadOnlyMemory<Char>, CancellationToken)
WriteAsync(String) WriteAsync(String) WriteAsync(String) WriteAsync(String)

Writes a string to the current string asynchronously.

WriteLine() WriteLine() WriteLine() WriteLine()

Writes a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean) WriteLine(Boolean)

Writes the text representation of a Boolean value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char) WriteLine(Char) WriteLine(Char) WriteLine(Char)

Writes a character followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char[]) WriteLine(Char[]) WriteLine(Char[]) WriteLine(Char[])

Writes an array of characters followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32) WriteLine(Char[], Int32, Int32)

Writes a subarray of characters followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Decimal) WriteLine(Decimal) WriteLine(Decimal) WriteLine(Decimal)

Writes the text representation of a decimal value followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(Double) WriteLine(Double) WriteLine(Double) 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)
WriteLine(Int32) WriteLine(Int32) WriteLine(Int32) 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)
WriteLine(Int64) WriteLine(Int64) WriteLine(Int64) 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)
WriteLine(Object) WriteLine(Object) WriteLine(Object) 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)
WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>) WriteLine(ReadOnlySpan<Char>)
WriteLine(Single) WriteLine(Single) WriteLine(Single) 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)
WriteLine(String) WriteLine(String) WriteLine(String) WriteLine(String)

Writes a string followed by a line terminator to the text string or stream.

(Inherited from TextWriter)
WriteLine(String, Object) WriteLine(String, Object) WriteLine(String, Object) WriteLine(String, Object)

Writes a formatted string and a new line to the text string or stream, using the same semantics as the Format(String, Object) method.

(Inherited from TextWriter)
WriteLine(String, Object, Object) WriteLine(String, Object, Object) WriteLine(String, Object, Object) WriteLine(String, Object, Object)

Writes a formatted string and a new line to the text string or stream, using the same semantics as the Format(String, Object, Object) method.

(Inherited from TextWriter)
WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object) WriteLine(String, Object, Object, Object)

Writes out a formatted string and a new line, using the same semantics as Format(String, Object).

(Inherited from TextWriter)
WriteLine(String, Object[]) WriteLine(String, Object[]) WriteLine(String, Object[]) WriteLine(String, Object[])

Writes out a formatted string and a new line, using the same semantics as Format(String, Object).

(Inherited from TextWriter)
WriteLine(UInt32) WriteLine(UInt32) WriteLine(UInt32) 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)
WriteLine(UInt64) WriteLine(UInt64) WriteLine(UInt64) 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)
WriteLineAsync() WriteLineAsync() WriteLineAsync() WriteLineAsync()

Writes a line terminator asynchronously to the text string or stream.

(Inherited from TextWriter)
WriteLineAsync(Char) WriteLineAsync(Char) WriteLineAsync(Char) WriteLineAsync(Char)

Writes a character followed by a line terminator asynchronously to the string.

WriteLineAsync(Char[]) WriteLineAsync(Char[]) WriteLineAsync(Char[]) WriteLineAsync(Char[])

Writes an array of characters followed by a line terminator asynchronously to the text string or stream.

(Inherited from TextWriter)
WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32) WriteLineAsync(Char[], Int32, Int32)

Writes a subarray of characters followed by a line terminator asynchronously to the string.

WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken) WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken)
WriteLineAsync(String) WriteLineAsync(String) WriteLineAsync(String) WriteLineAsync(String)

Writes a string followed by a line terminator asynchronously to the current string.

Fields

CoreNewLine CoreNewLine CoreNewLine CoreNewLine

Stores the newline characters used for this TextWriter.

(Inherited from TextWriter)

Explicit Interface Implementations

IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() IDisposable.Dispose() Inherited from TextWriter

Applies to

See Also