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 任务。