Bewerken

Share via


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
public class StringWriter : System.IO.TextWriter
[System.Serializable]
public class StringWriter : System.IO.TextWriter
[System.Serializable]
[System.Runtime.InteropServices.ComVisible(true)]
public class StringWriter : System.IO.TextWriter
type StringWriter = class
    inherit TextWriter
[<System.Serializable>]
type StringWriter = class
    inherit TextWriter
[<System.Serializable>]
[<System.Runtime.InteropServices.ComVisible(true)>]
type StringWriter = class
    inherit TextWriter
Public Class StringWriter
Inherits TextWriter
Inheritance
StringWriter
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 = (char)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 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()

Initializes a new instance of the StringWriter class.

StringWriter(IFormatProvider)

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

StringWriter(StringBuilder, IFormatProvider)

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

StringWriter(StringBuilder)

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

Fields

CoreNewLine

Stores the newline characters used for this TextWriter.

(Inherited from TextWriter)

Properties

Encoding

Gets the Encoding in which the output is written.

FormatProvider

Gets an object that controls formatting.

(Inherited from TextWriter)
NewLine

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

(Inherited from TextWriter)

Methods

Close()

Closes the current StringWriter and the underlying stream.

Close()

Closes the current writer and releases any system resources associated with the writer.

(Inherited from TextWriter)
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()

Releases all resources used by the TextWriter object.

(Inherited from TextWriter)
Dispose(Boolean)

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

DisposeAsync()

Asynchronously releases all resources used by the TextWriter object.

(Inherited from TextWriter)
Equals(Object)

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

(Inherited from Object)
Flush()

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

(Inherited from TextWriter)
FlushAsync()

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

FlushAsync()

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

(Inherited from TextWriter)
FlushAsync(CancellationToken)

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

(Inherited from TextWriter)
GetHashCode()

Serves as the default hash function.

(Inherited from Object)
GetLifetimeService()
Obsolete.

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

(Inherited from MarshalByRefObject)
GetStringBuilder()

Returns the underlying StringBuilder.

GetType()

Gets the Type of the current instance.

(Inherited from Object)
InitializeLifetimeService()
Obsolete.

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

(Inherited from MarshalByRefObject)
MemberwiseClone()

Creates a shallow copy of the current Object.

(Inherited from Object)
MemberwiseClone(Boolean)

Creates a shallow copy of the current MarshalByRefObject object.

(Inherited from MarshalByRefObject)
ToString()

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

Write(Boolean)

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

(Inherited from TextWriter)
Write(Char)

Writes a character to the string.

Write(Char[], Int32, Int32)

Writes a subarray of characters to the string.

Write(Char[])

Writes a character array to the text stream.

(Inherited from TextWriter)
Write(Decimal)

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

(Inherited from TextWriter)
Write(Double)

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

(Inherited from TextWriter)
Write(Int32)

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

(Inherited from TextWriter)
Write(Int64)

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

(Inherited from TextWriter)
Write(Object)

Writes the text representation of an object to the text stream by calling the ToString method on that object.

(Inherited from TextWriter)
Write(ReadOnlySpan<Char>)

Writes the string representation of a span of chars to the current string.

Write(ReadOnlySpan<Char>)

Writes a character span to the text stream.

(Inherited from TextWriter)
Write(Single)

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

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

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

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

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

(Inherited from TextWriter)
Write(String, Object)

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

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

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

(Inherited from TextWriter)
Write(String, ReadOnlySpan<Object>)

Writes a formatted string to the text stream, using the same semantics as Format(String, ReadOnlySpan<Object>).

(Inherited from TextWriter)
Write(String)

Writes a string to the current string.

Write(StringBuilder)

Writes the string representation of a string builder to the current string.

Write(StringBuilder)

Writes a string builder to the text stream.

(Inherited from TextWriter)
Write(UInt32)

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

(Inherited from TextWriter)
Write(UInt64)

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

(Inherited from TextWriter)
WriteAsync(Char)

Writes a character to the string asynchronously.

WriteAsync(Char)

Writes a character to the text stream asynchronously.

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

Writes a subarray of characters to the string asynchronously.

WriteAsync(Char[], Int32, Int32)

Writes a subarray of characters to the text stream asynchronously.

(Inherited from TextWriter)
WriteAsync(Char[])

Writes a character array to the text stream asynchronously.

(Inherited from TextWriter)
WriteAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes a memory region of characters to the string.

WriteAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes a character memory region to the text stream.

(Inherited from TextWriter)
WriteAsync(String)

Writes a string to the current string asynchronously.

WriteAsync(String)

Writes a string to the text stream asynchronously.

(Inherited from TextWriter)
WriteAsync(StringBuilder, CancellationToken)

Asynchronously writes the text representation of a string builder to the string.

WriteAsync(StringBuilder, CancellationToken)

Asynchronously writes a string builder to the text stream.

(Inherited from TextWriter)
WriteLine()

Writes a line terminator to the text stream.

(Inherited from TextWriter)
WriteLine(Boolean)

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

(Inherited from TextWriter)
WriteLine(Char)

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

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

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

(Inherited from TextWriter)
WriteLine(Char[])

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

(Inherited from TextWriter)
WriteLine(Decimal)

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

(Inherited from TextWriter)
WriteLine(Double)

Writes the text representation of a 8-byte floating-point value to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(Int32)

Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(Int64)

Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(Object)

Writes the text representation of an object to the text stream, by calling the ToString method on that object, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(ReadOnlySpan<Char>)

Writes the text representation a span of characters to the string, followed by a line terminator.

WriteLine(ReadOnlySpan<Char>)

Writes the text representation of a character span to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(Single)

Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator.

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

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

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

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

(Inherited from TextWriter)
WriteLine(String, Object)

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

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

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

(Inherited from TextWriter)
WriteLine(String, ReadOnlySpan<Object>)

Writes out a formatted string and a new line to the text stream, using the same semantics as Format(String, ReadOnlySpan<Object>).

(Inherited from TextWriter)
WriteLine(String)

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

(Inherited from TextWriter)
WriteLine(StringBuilder)

Writes the text representation of a string builder to the string, followed by a line terminator.

WriteLine(StringBuilder)

Writes the text representation of a string builder to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(UInt32)

Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLine(UInt64)

Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLineAsync()

Asynchronously writes a line terminator to the text stream.

(Inherited from TextWriter)
WriteLineAsync(Char)

Asynchronously writes a character to the string, followed by a line terminator.

WriteLineAsync(Char)

Asynchronously writes a character to the text stream, followed by a line terminator.

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

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

WriteLineAsync(Char[], Int32, Int32)

Asynchronously writes a subarray of characters to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLineAsync(Char[])

Asynchronously writes an array of characters to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes the string representation of the memory region of characters to the current string, followed by a line terminator.

WriteLineAsync(ReadOnlyMemory<Char>, CancellationToken)

Asynchronously writes the text representation of a character memory region to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLineAsync(String)

Asynchronously writes a string to the current string, followed by a line terminator.

WriteLineAsync(String)

Asynchronously writes a string to the text stream, followed by a line terminator.

(Inherited from TextWriter)
WriteLineAsync(StringBuilder, CancellationToken)

Asynchronously writes the string representation of the string builder to the current string, followed by a line terminator.

WriteLineAsync(StringBuilder, CancellationToken)

Asynchronously writes the text representation of a string builder to the text stream, followed by a line terminator.

(Inherited from TextWriter)

Explicit Interface Implementations

IDisposable.Dispose()

For a description of this member, see Dispose().

(Inherited from TextWriter)

Extension Methods

ConfigureAwait(IAsyncDisposable, Boolean)

Configures how awaits on the tasks returned from an async disposable will be performed.

Applies to

See also