以块的形式读取大文件 c# [英] Reading large file in chunks c#

查看:30
本文介绍了以块的形式读取大文件 c#的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想逐块读取非常大的文件(4GBish).

I want to read very large file (4GBish) chunk by chunk.

我目前正在尝试使用 StreamReaderRead() 读取方法.语法是:

I am currently trying to use a StreamReader and the Read() read method. The syntax is:

sr.Read(char[] buffer, int index, int count)

因为 index 是一个 int,在我的例子中它会溢出.我应该用什么代替?

Because the index is an int it will overflow in my case. What should i use instead?

推荐答案

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.

这篇关于以块的形式读取大文件 c#的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆