StringWriter 类

定义

实现一个用于将信息写入字符串的 TextWriterImplements a TextWriter for writing information to a string. 该信息存储在基础 StringBuilder 中。The information is stored in an underlying StringBuilder.

public ref class StringWriter : System::IO::TextWriter
[System.Runtime.InteropServices.ComVisible(true)]
[System.Serializable]
public class StringWriter : System.IO.TextWriter
type StringWriter = class
    inherit TextWriter
Public Class StringWriter
Inherits TextWriter
继承
属性

示例

下面的代码示例演示了如何从一组双倍间距的句子创建连续段落, 然后将段落转换回原始文本。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 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

注解

StringWriter使您能够同步或异步写入字符串。StringWriter enables you to write to a string synchronously or asynchronously. 您可以使用Write(Char)或方法一次WriteAsync(Char)写入一个字符, 使用Write(String)WriteAsync(String)方法一次写入一个字符串。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. 此外, 还可以使用其中一种WriteLineAsync方法, 以异步方式编写字符、字符数组或后跟行结束符的字符串。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.

备注

此类型可实现 IDisposable 接口,但实际上没有任何要释放的资源。This type implements the IDisposable interface, but does not actually have any resources to dispose. 这意味着无需通过直接调用 Dispose() 或使用语言构造(C# 中的 using 或 Visual Basic 中的 Using)对其进行处理。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.

下表列出了其他典型或相关 i/o 任务的示例。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

构造函数

StringWriter()

初始化 StringWriter 类的新实例。Initializes a new instance of the StringWriter class.

StringWriter(IFormatProvider)

使用指定的格式控制初始化 StringWriter 类的新实例。Initializes a new instance of the StringWriter class with the specified format control.

StringWriter(StringBuilder)

初始化写入指定 StringWriterStringBuilder 类的新实例。Initializes a new instance of the StringWriter class that writes to the specified StringBuilder.

StringWriter(StringBuilder, IFormatProvider)

初始化写入指定 StringWriter 并具有指定格式提供程序的 StringBuilder 类的新实例。Initializes a new instance of the StringWriter class that writes to the specified StringBuilder and has the specified format provider.

字段

CoreNewLine

存储用于此 TextWriter 的换行符。Stores the newline characters used for this TextWriter.

(继承自 TextWriter)

属性

Encoding

获取在其中写入输出的 EncodingGets the Encoding in which the output is written.

FormatProvider

获取控制格式设置的对象。Gets an object that controls formatting.

(继承自 TextWriter)
NewLine

获取或设置由当前 TextWriter 使用的行结束符字符串。Gets or sets the line terminator string used by the current TextWriter.

(继承自 TextWriter)

方法

Close()

关闭当前的 StringWriter 和基础流。Closes the current StringWriter and the underlying stream.

CreateObjRef(Type)

创建一个对象,该对象包含生成用于与远程对象进行通信的代理所需的全部相关信息。Creates an object that contains all the relevant information required to generate a proxy used to communicate with a remote object.

(继承自 MarshalByRefObject)
Dispose()

释放由 TextWriter 对象使用的所有资源。Releases all resources used by the TextWriter object.

(继承自 TextWriter)
Dispose(Boolean)

释放由 StringWriter 占用的非托管资源,还可以另外再释放托管资源。Releases the unmanaged resources used by the StringWriter and optionally releases the managed resources.

DisposeAsync()

异步释放由 TextWriter 对象使用的所有资源。Asynchronously releases all resources used by the TextWriter object.

(继承自 TextWriter)
Equals(Object)

确定指定的对象是否等于当前对象。Determines whether the specified object is equal to the current object.

(继承自 Object)
Flush()

清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。Clears all buffers for the current writer and causes any buffered data to be written to the underlying device.

(继承自 TextWriter)
FlushAsync()

异步清理当前编写器的所有缓冲区,使所有缓冲数据写入基础设备。Asynchronously clears all buffers for the current writer and causes any buffered data to be written to the underlying device.

GetHashCode()

用作默认哈希函数。Serves as the default hash function.

(继承自 Object)
GetLifetimeService()

检索控制此实例的生存期策略的当前生存期服务对象。Retrieves the current lifetime service object that controls the lifetime policy for this instance.

(继承自 MarshalByRefObject)
GetStringBuilder()

返回基础 StringBuilderReturns the underlying StringBuilder.

GetType()

获取当前实例的 TypeGets the Type of the current instance.

(继承自 Object)
InitializeLifetimeService()

获取生存期服务对象来控制此实例的生存期策略。Obtains a lifetime service object to control the lifetime policy for this instance.

(继承自 MarshalByRefObject)
MemberwiseClone()

创建当前 Object 的浅表副本。Creates a shallow copy of the current Object.

(继承自 Object)
MemberwiseClone(Boolean)

创建当前 MarshalByRefObject 对象的浅表副本。Creates a shallow copy of the current MarshalByRefObject object.

(继承自 MarshalByRefObject)
ToString()

返回包含迄今为止写入到当前 StringWriter 中的字符的字符串。Returns a string containing the characters written to the current StringWriter so far.

Write(Boolean)

Boolean 值的文本表示形式写入文本流。Writes the text representation of a Boolean value to the text stream.

(继承自 TextWriter)
Write(Char)

将字符写入该字符串。Writes a character to the string.

Write(Char[])

将字符数组写入文本流。Writes a character array to the text stream.

(继承自 TextWriter)
Write(Char[], Int32, Int32)

将字符的子数组写入该字符串。Writes a subarray of characters to the string.

Write(Decimal)

将小数值的文本表示形式写入文本流。Writes the text representation of a decimal value to the text stream.

(继承自 TextWriter)
Write(Double)

将 8 字节浮点值的文本表示形式写入文本流。Writes the text representation of an 8-byte floating-point value to the text stream.

(继承自 TextWriter)
Write(Int32)

将 4 字节带符号整数的文本表示形式写入文本流。Writes the text representation of a 4-byte signed integer to the text stream.

(继承自 TextWriter)
Write(Int64)

将 8 字节带符号整数的文本表示形式写入文本流。Writes the text representation of an 8-byte signed integer to the text stream.

(继承自 TextWriter)
Write(Object)

通过在对象上调用 ToString 方法将此对象的文本表示形式写入文本流。Writes the text representation of an object to the text stream by calling the ToString method on that object.

(继承自 TextWriter)
Write(ReadOnlySpan<Char>)

将字符范围的字符串表示形式写入当前字符串。Writes the string representation of a span of chars to the current string.

Write(Single)

将 4 字节浮点值的文本表示形式写入文本流。Writes the text representation of a 4-byte floating-point value to the text stream.

(继承自 TextWriter)
Write(String)

将字符串写入当前流。Writes a string to the current string.

Write(String, Object)

使用与 Format(String, Object) 方法相同的语义将格式化字符串写入文本流。Writes a formatted string to the text stream, using the same semantics as the Format(String, Object) method.

(继承自 TextWriter)
Write(String, Object, Object)

使用与 Format(String, Object, Object) 方法相同的语义将格式化字符串写入文本流。Writes a formatted string to the text stream using the same semantics as the Format(String, Object, Object) method.

(继承自 TextWriter)
Write(String, Object, Object, Object)

使用与 Format(String, Object, Object, Object) 方法相同的语义将格式化字符串写入文本流。Writes a formatted string to the text stream, using the same semantics as the Format(String, Object, Object, Object) method.

(继承自 TextWriter)
Write(String, Object[])

使用与 Format(String, Object[]) 方法相同的语义将格式化字符串写入文本流。Writes a formatted string to the text stream, using the same semantics as the Format(String, Object[]) method.

(继承自 TextWriter)
Write(StringBuilder)

将字符串生成器的字符串表示形式写入当前字符串。Writes the string representation of a string builder to the current string.

Write(UInt32)

将 4 字节无符号整数的文本表示形式写入文本流。Writes the text representation of a 4-byte unsigned integer to the text stream.

(继承自 TextWriter)
Write(UInt64)

将 8 字节无符号整数的文本表示形式写入文本流。Writes the text representation of an 8-byte unsigned integer to the text stream.

(继承自 TextWriter)
WriteAsync(Char)

以异步方式将字符写入流。Writes a character to the string asynchronously.

WriteAsync(Char[])

将字符数组异步写入文本流。Writes a character array to the text stream asynchronously.

(继承自 TextWriter)
WriteAsync(Char[], Int32, Int32)

将字符的子数组异步写入该字符串。Writes a subarray of characters to the string asynchronously.

WriteAsync(ReadOnlyMemory<Char>, CancellationToken)

将字符的内存区域异步写入字符串。Asynchronously writes a memory region of characters to the string.

WriteAsync(String)

以异步方式将字符串写入当前流。Writes a string to the current string asynchronously.

WriteAsync(StringBuilder, CancellationToken)

将字符串生成器的文本表示形式异步写入字符串。Asynchronously writes the text representation of a string builder to the string.

WriteLine()

将行终止符写入文本流。Writes a line terminator to the text stream.

(继承自 TextWriter)
WriteLine(Boolean)

Boolean 值的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a Boolean value to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Char)

将字符写入文本流,后跟行终止符。Writes a character to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Char[])

将字符数组写入文本流,后跟行终止符。Writes an array of characters to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Char[], Int32, Int32)

将字符子数组写入文本流,后跟行终止符。Writes a subarray of characters to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Decimal)

将小数值的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a decimal value to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Double)

将 8 字节浮点值的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a 8-byte floating-point value to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Int32)

将 4 字节带符号整数的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a 4-byte signed integer to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Int64)

将 8 字节带符号整数的文本表示形式写入文本流,后跟行终止符。Writes the text representation of an 8-byte signed integer to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(Object)

通过在对象上调用 ToString 方法将此对象的文本表示形式写入文本流,后跟行终止符。Writes the text representation of an object to the text stream, by calling the ToString method on that object, followed by a line terminator.

(继承自 TextWriter)
WriteLine(ReadOnlySpan<Char>)

将字符范围的文本表示形式写入字符串,后跟行终止符。Writes the text representation a span of characters to the string, followed by a line terminator.

WriteLine(Single)

将 4 字节浮点值的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a 4-byte floating-point value to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(String)

将字符串写入文本流,后跟行终止符。Writes a string to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(String, Object)

使用与 Format(String, Object) 方法相同的语义将格式化字符串和新行写入文本流。Writes a formatted string and a new line to the text stream, using the same semantics as the Format(String, Object) method.

(继承自 TextWriter)
WriteLine(String, Object, Object)

使用与 Format(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.

(继承自 TextWriter)
WriteLine(String, Object, Object, Object)

使用与 Format(String, Object) 相同的语义将格式化字符串和新行写入文本流。Writes out a formatted string and a new line to the text stream, using the same semantics as Format(String, Object).

(继承自 TextWriter)
WriteLine(String, Object[])

使用与 Format(String, Object) 相同的语义将格式化字符串和新行写入文本流。Writes out a formatted string and a new line to the text stream, using the same semantics as Format(String, Object).

(继承自 TextWriter)
WriteLine(StringBuilder)

将字符串生成器的文本表示形式写入字符串,后跟行终止符。Writes the text representation of a string builder to the string, followed by a line terminator.

WriteLine(UInt32)

将 4 字节无符号整数的文本表示形式写入文本流,后跟行终止符。Writes the text representation of a 4-byte unsigned integer to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLine(UInt64)

将 8 字节无符号整数的文本表示形式写入文本流,后跟行终止符。Writes the text representation of an 8-byte unsigned integer to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLineAsync()

以异步形式将行终止符写入文本流。Asynchronously writes a line terminator to the text stream.

(继承自 TextWriter)
WriteLineAsync(Char)

将字符异步写入字符串,后跟行终止符。Asynchronously writes a character to the string, followed by a line terminator.

WriteLineAsync(Char[])

以异步形式将字符数组写入文本流,后跟行终止符。Asynchronously writes an array of characters to the text stream, followed by a line terminator.

(继承自 TextWriter)
WriteLineAsync(Char[], Int32, Int32)

将字符的子数组异步写入字符串,后跟行终止符。asynchronously writes a subarray of characters to the string, followed by a line terminator.

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(String)

将字符串异步写入当前字符串,后跟行终止符。Asynchronously writes a string to the current string, followed by a line terminator.

WriteLineAsync(StringBuilder, CancellationToken)

将字符串生成器的字符串表示形式异步写入当前字符串,后跟行终止符。Asynchronously writes the string representation of the string builder to the current string, followed by a line terminator.

显式界面实现

IDisposable.Dispose()

有关此成员的说明,请参见 Dispose()For a description of this member, see Dispose().

(继承自 TextWriter)

适用于

另请参阅