繁体   English   中英

C#Filestream Read-回收数组?

[英]C# Filestream Read - Recycle array?

我正在使用读取的文件流: https ://msdn.microsoft.com/zh-cn/library/system.io.filestream.read%28v=vs.110%29.aspx

我想做的是一次在循环中读取一个大文件,每次读取一定数量的字节。 一次不整个文件。 代码示例显示了以下内容:

int n = fsSource.Read(bytes, numBytesRead, numBytesToRead);

“字节”的定义是:“当此方法返回时,包含指定的字节数组,其值介于offset和(offset + count-1)之间,并替换为从当前源读取的字节。”

我想一次只读1 mb,所以我这样做:

using (FileStream fsInputFile = new FileStream(strInputFileName, FileMode.Open, FileAccess.Read)) {

int intBytesToRead = 1024;
int intTotalBytesRead = 0;
int intInputFileByteLength = 0;
byte[] btInputBlock = new byte[intBytesToRead];
byte[] btOutputBlock = new byte[intBytesToRead];

intInputFileByteLength = (int)fsInputFile.Length;

while (intInputFileByteLength - 1 >= intTotalBytesRead)
{
    if (intInputFileByteLength - intTotalBytesRead < intBytesToRead)
    {
        intBytesToRead = intInputFileByteLength - intTotalBytesRead;
    }

    // *** Problem is here ***
    int n = fsInputFile.Read(btInputBlock, intTotalBytesRead, intBytesToRead); 

    intTotalBytesRead += n;

    fsOutputFile.Write(btInputBlock, intTotalBytesRead - n, n);
}

fsOutputFile.Close(); }

在指出问题区域的地方,btInputBlock在第一个周期工作,因为它读取1024个字节。 但是,在第二个循环中,它不会回收此字节数组。 相反,它尝试将新的1024个字节附加到btInputBlock中。 据我所知,您只能指定要读取的文件的偏移量和长度,而不能指定btInputBlock的偏移量和长度。 有没有一种方法可以“重用” Filestream.Read转储到的数组,还是应该找到其他解决方案?

谢谢。

PS读取的例外是:“数组的偏移量和长度超出范围,或者计数大于从索引到源集合末尾的元素数。”

您的代码可以简化一些

int num;
byte[] buffer = new byte[1024];
while ((num = fsInputFile.Read(buffer, 0, buffer.Length)) != 0)
{
     //Do your work here
     fsOutputFile.Write(buffer, 0, num);
}

请注意, Read接收要填充Array偏移量 (即应放置字节的数组的偏移量,以及read的(最大) 字节数

那是因为您要增加intTotalBytesRead,它是数组的偏移量,而不是文件流的偏移量。 在您的情况下,它应该始终为零,这将覆盖数组中的前一个字节数据,而不是使用intTotalBytesRead将其追加到末尾。

int n = fsInputFile.Read(btInputBlock, intTotalBytesRead, intBytesToRead); //currently
int n = fsInputFile.Read(btInputBlock, 0, intBytesToRead); //should be

Filestream不需要偏移量,每个Read都从上次中断的地方开始。 有关详细信息,请参见https://msdn.microsoft.com/zh-cn/library/system.io.filestream.read(v=vs.110).aspx

您的Read调用应为Read(btInputBlock, 0, intBytesToRead) 第二个参数是您要开始将字节写入其中的数组的偏移量。 类似地,对于Write您希望Write(btInputBlock, 0, n)作为第二个参数是数组中要从其开始写入字节的偏移量。 另外,您也不需要调用Close因为using会为您清理FileStream

using (FileStream fsInputFile = new FileStream(strInputFileName, FileMode.Open, FileAccess.Read)) 
{
    int intBytesToRead = 1024;
    byte[] btInputBlock = new byte[intBytesToRead];

    while (fsInputFile.Postion < fsInputFile.Length)
    {
        int n = fsInputFile.Read(btInputBlock, 0, intBytesToRead); 
        intTotalBytesRead += n;
        fsOutputFile.Write(btInputBlock, 0, n);
    }
}

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM