StreamReader.ReadLine 方法
定義
重要
部分資訊涉及發行前產品,在發行之前可能會有大幅修改。 Microsoft 對此處提供的資訊,不做任何明確或隱含的瑕疵擔保。
自目前資料流讀取一行字元,並將資料以字串傳回。
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
(如果已到達輸入資料流末端)。
例外狀況
沒有足夠記憶體可為傳回的字串配置緩衝區。
發生 I/O 錯誤。
範例
下列程式碼範例會從檔案讀取行,直到到達檔案結尾為止。
using namespace System;
using namespace System::IO;
int main()
{
String^ path = "c:\\temp\\MyTest.txt";
try
{
if ( File::Exists( path ) )
{
File::Delete( path );
}
StreamWriter^ sw = gcnew StreamWriter( path );
try
{
sw->WriteLine( "This" );
sw->WriteLine( "is some text" );
sw->WriteLine( "to test" );
sw->WriteLine( "Reading" );
}
finally
{
delete sw;
}
StreamReader^ sr = gcnew StreamReader( path );
try
{
while ( sr->Peek() >= 0 )
{
Console::WriteLine( sr->ReadLine() );
}
}
finally
{
delete sr;
}
}
catch ( Exception^ e )
{
Console::WriteLine( "The process failed: {0}", e );
}
}
using System;
using System.IO;
class Test
{
public static void Main()
{
string path = @"c:\temp\MyTest.txt";
try
{
if (File.Exists(path))
{
File.Delete(path);
}
using (StreamWriter sw = new StreamWriter(path))
{
sw.WriteLine("This");
sw.WriteLine("is some text");
sw.WriteLine("to test");
sw.WriteLine("Reading");
}
using (StreamReader sr = new StreamReader(path))
{
while (sr.Peek() >= 0)
{
Console.WriteLine(sr.ReadLine());
}
}
}
catch (Exception e)
{
Console.WriteLine("The process failed: {0}", e.ToString());
}
}
}
Imports System.IO
Imports System.Text
Public Class Test
Public Shared Sub Main()
Dim path As String = "c:\temp\MyTest.txt"
Try
If File.Exists(path) Then
File.Delete(path)
End If
Dim sw As StreamWriter = New StreamWriter(path)
sw.WriteLine("This")
sw.WriteLine("is some text")
sw.WriteLine("to test")
sw.WriteLine("Reading")
sw.Close()
Dim sr As StreamReader = New StreamReader(path)
Do While sr.Peek() >= 0
Console.WriteLine(sr.ReadLine())
Loop
sr.Close()
Catch e As Exception
Console.WriteLine("The process failed: {0}", e.ToString())
End Try
End Sub
End Class
備註
行定義為字元序列,後面接著換行字元 ( "\n" ) 、換行字元 ( "\r" ) 或緊接在換行字元 ( "\r\n" ) 的換行字元。 傳回的字串不包含終止的回車或換行字元。 null
如果到達輸入資料流程的結尾,則傳回的值為。
這個方法會覆寫 TextReader.ReadLine。
如果目前的方法擲回 OutOfMemoryException ,則讀取器在基礎物件中的位置 Stream 會由方法可以讀取的字元數進行前移,但已讀入內部緩衝區的字元 ReadLine 會被捨棄。 如果您在將資料讀入緩衝區後操作基礎資料流程的位置,則基礎資料流程的位置可能不符合內部緩衝區的位置。 若要重設內部緩衝區,請呼叫 DiscardBufferedData 方法; 不過,這個方法會降低效能,而且只有在絕對必要時才會呼叫。
如需一般 i/o 工作的清單,請參閱 一般 i/o工作。