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 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 到达输入流的末尾时。
如果流以换行序列结尾,则不会返回其他空行。 例如,包含"line1\nline2\n"的流生成与包含"line1\nline2"的流相同的两行("line1"和"line2")。
此方法重写 TextReader.ReadLine。
如果当前方法引发一个 OutOfMemoryException,则该方法能够读取的字符数会高级读取器在基础 Stream 对象中的位置,但已读入内部 ReadLine 缓冲区的字符将被丢弃。 如果在将数据读取到缓冲区后操作基础流的位置,则基础流的位置可能与内部缓冲区的位置不匹配。 若要重置内部缓冲区,请调用 DiscardBufferedData 该方法;但是,此方法会降低性能,并且仅当绝对必要时才应调用。
有关常见 I/O 任务的列表,请参阅 常见 I/O 任务。