且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

以块的形式读取大文件 c#

更新时间:2023-12-06 17:03:28

index 是缓冲区的起始索引而不是文件指针的索引,通常为零.在每个 Read 调用中,您将读取等于 Read 方法的 count 参数的字符.您不会一次读取所有文件,而是分块读取并使用该块.

The index is the starting index of buffer not the index of file pointer, usually it would be zero. On each Read call you will read characters equal to the count parameter of Read method. You would not read all the file at once rather read in chunks and use that chunk.

开始写入的缓冲区索引,参考.

The index of buffer at which to begin writing, reference.

char[] c = null;
while (sr.Peek() >= 0) 
{
    c = new char[1024];
    sr.Read(c, 0, c.Length);
    //The output will look odd, because 
    //only five characters are read at a time.
    Console.WriteLine(c);
}

上面的例子将准备好 1024 个字节并将写入控制台.您可以使用这些字节,例如使用 TCP 连接将这些字节发送到其他应用程序.

The above example will ready 1024 bytes and will write to console. You can use these bytes, for instance sending these bytes to other application using TCP connection.

当使用 Read 方法时,使用缓冲区更有效与流的内部缓冲区大小相同,其中内部缓冲区设置为您所需的块大小,并始终读取小于块大小.如果内部缓冲区的大小是在构建流时未指定,其默认大小为 4千字节(4096 字节),MSDN.

When using the Read method, it is more efficient to use a buffer that is the same size as the internal buffer of the stream, where the internal buffer is set to your desired block size, and to always read less than the block size. If the size of the internal buffer was unspecified when the stream was constructed, its default size is 4 kilobytes (4096 bytes), MSDN.