如何读取任意文件并“逐个”处理它(意味着逐字节或其他一些可以提供最佳读取性能的块大小)而不将整个文件加载到内存中?处理的一个示例是生成文件的 MD5 哈希值,尽管答案可以适用于任何操作。
我想拥有或编写这个,但如果我可以获得现有的代码,那就太好了。
(c#)
下面是如何以 1KB 为单位读取文件而不将整个内容加载到内存中的示例:
const int chunkSize = 1024; // read the file by chunks of 1KB
using (var file = File.OpenRead("foo.dat"))
{
int bytesRead;
var buffer = new byte[chunkSize];
while ((bytesRead = file.Read(buffer, 0, buffer.Length)) > 0)
{
// TODO: Process bytesRead number of bytes from the buffer
// not the entire buffer as the size of the buffer is 1KB
// whereas the actual number of bytes that are read are
// stored in the bytesRead integer.
}
}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)