StringReader.ReadLine 方法

定義

自目前字串讀取一行字元,並將資料以字串傳回。

public:
 override System::String ^ ReadLine();
public override string ReadLine ();
public override string? ReadLine ();
override this.ReadLine : unit -> string
Public Overrides Function ReadLine () As String

傳回

目前字串的下一行,如果已到達字串的結尾,則為 null

例外狀況

目前的讀取器已關閉。

沒有足夠記憶體可為傳回的字串配置緩衝區。

範例

此程式代碼範例是針對 類別提供的較大範例的 StringReader 一部分。

// 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 );
// 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);
' 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)

備註

這個方法會 TextReader.ReadLine 覆寫 方法。

行定義為字元序列,後面接著換行字元 (“\n”) 、歸位字元 (“\r”) 、換行字元緊接 (“\r\n”) 或數據流結尾標記。 傳回的字串不包含終止歸位字元或換行字元。 如果已達到資料流結尾標記,則傳回的值為 null 。 也就是說,如果最後一行讀取和數據流結尾標記之間沒有任何專案,則方法會傳 null回 。

如果目前的方法擲回 OutOfMemoryException,則基礎字串中的讀取器位置會由方法能夠讀取的字元數進階,但已讀取內部緩衝區的 ReadLine 字元會被捨棄。 因為無法變更字串中讀取器的位置,所以已經讀取的字元無法復原,而且只能藉由重新初始化 StringReader來存取。 若要避免這種情況,請使用 Read 方法,並將讀取字元儲存在預先配置的緩衝區中。

下表列出其他一般或相關 I/O 工作的範例。

作法... 請參閱這個主題中的範例…
建立文字檔 作法:將文字寫入檔案
寫入文字檔。 作法:將文字寫入檔案
從文字檔讀取。 作法:讀取檔案中的文字
將文字附加至檔案。 作法:開啟並附加至記錄檔

File.AppendText

FileInfo.AppendText
取得檔案的大小。 FileInfo.Length
取得檔案的屬性。 File.GetAttributes
設定檔案的屬性。 File.SetAttributes
判斷檔案是否存在。 File.Exists
從二進位檔讀取。 作法:讀取和寫入新建立的資料檔案
寫入二進位檔。 作法:讀取和寫入新建立的資料檔案

適用於

另請參閱