System.IO.StreamReader.ReadLine 方法

方法描述

从当前流中读取一行字符并将数据作为字符串返回。

语法定义(C# System.IO.StreamReader.ReadLine 方法 的用法)

public override string ReadLine()

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
返回值 System.String 输入流中的下一行;如果到达了输入流的末尾,则为 null。

提示和注释

将行定义为后面跟有下列符号的字符序列:换行符(“\n”)、回车符(“\r”)或后跟换行符的回车符(“\r\n”)。 返回的字符串不包含终止回车或换行符。 如果到达了输入流的末尾,返回值为 null。

此方法重写 ReadLine。

如果当前方法引发 OutOfMemoryException,则读取器在基础 Stream 对象中的位置会向前移动此方法能够读取的字符数,而已经读入内部 ReadLine 缓冲区中的字符将被丢弃。 如果在将数据读取到缓冲区后操作基础流的位置,则基础刘的位置可能不匹配内部缓冲区的位置。 要重置内部缓冲区,请调用 DiscardBufferedData方法;但是,此方法会降低性能,并且只应在绝对必要时调用。

有关通用 I/O 任务的列表,请参见通用 I/O 任务。

System.IO.StreamReader.ReadLine 方法例子

下面的代码示例从文件中读取行,一直读到文件尾。

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());
        }
    }
}

异常

异常 异常描述
OutOfMemoryException 内存不足,无法为返回的字符串分配缓冲区。
IOException 发生 I/O 错误。

命名空间

namespace: System.IO

程序集: mscorlib(在 mscorlib.dll 中)

版本信息

.NET Framework 受以下版本支持:4、3.5、3.0、2.0、1.1、1.0 .NET Framework Client Profile 受以下版本支持:4、3.5 SP1 受以下版本支持:

适用平台

Windows 7, Windows Vista SP1 或更高版本, Windows XP SP3, Windows XP SP2 x64 Edition, Windows Server 2008(不支持服务器核心), Windows Server 2008 R2(支持 SP1 或更高版本的服务器核心), Windows Server 2003 SP2 .NET Framework 并不是对每个平台的所有版本都提供支持。有关支持的版本的列表,请参见.NET Framework 系统要求。