System.IO.StreamReader.Read 方法 (Char[], Int32, Int32)

方法描述

从当前流中将指定的最多个字符读到指定索引位置开始的缓冲区。

语法定义(C# System.IO.StreamReader.Read 方法 (Char[], Int32, Int32) 的用法)

public override int Read(
	char[] buffer,
	int index,
	int count
)

参数/返回值

参数值/返回值 参数类型/返回类型 参数描述/返回描述
buffer System-Char[] 此方法返回时,包含指定的字符数组,该数组的 index 和 (index + count - 1) 之间的值由从当前源中读取的字符替换。
index System-Int32 开始写入的 buffer 的索引。
count System-Int32 最多读取的字符数。
返回值 System.Int32 已读取的字符数,或者如果已到达流的末尾并且未读取任何数据,则为 0。 该数小于或等于 count 参数,具体取决于流中是否有可用的数据。

提示和注释

此方法重写 Read。

此方法返回一个整数,以便在到达流的末尾时可以返回 0。

使用 Read 方法时,较为高效的方法是使用与流的内部缓冲区大小一致的缓冲区,其中内部缓冲区设置为您想要的块大小,并始终读取小于此块大小的内容。 如果构造流时未指定内部缓冲区大小,则缓冲区的默认大小为 4 KB(4096 字节)。 如果在将数据读取到缓冲区后操作基础流的位置,则基础刘的位置可能不匹配内部缓冲区的位置。 要重置内部缓冲区,请调用 DiscardBufferedData方法;但是,此方法会降低性能,并且只应在绝对必要时调用。

在读取 count 参数指定的字符数或到达文件末尾之后,此方法将返回。 ReadBlock 是 Read 的条块化版本。

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

System.IO.StreamReader.Read 方法 (Char[], Int32, Int32)例子

下面的代码示例一次读取五个字符,直至到达文件的末尾。

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)) 
            {
                //This is an arbitrary size for this example.
                char[] c = null;

                while (sr.Peek() >= 0) 
                {
                    c = new char[5];
                    sr.Read(c, 0, c.Length);
                    //The output will look odd, because
                    //only five characters are read at a time.
                    Console.WriteLine(c);
                }
            }
        } 
        catch (Exception e) 
        {
            Console.WriteLine("The process failed: {0}", e.ToString());
        }
    }
}

异常

异常 异常描述
ArgumentException 缓冲区长度减去 index 小于 count。
ArgumentNullException buffer 为 null。
ArgumentOutOfRangeException index 或 count 为负。
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 系统要求。