我有一些C#代码要调用TF(true,"C:\input.txt","C:\noexistsyet.file")
,但是当我运行它时,它会在FileStream.Read()
上中断,以便将文件的最后一个块读入缓冲区,从而获得索引输出-bounds ArgumentException
。
对我来说,代码似乎是合乎逻辑的,没有溢出来尝试写入缓冲区。我以为我已经设置了rdlen
和_chunk
,但也许我看错了。有什么帮助吗?
我的错误:ArgumentException was unhandled: Offset and length were out of bounds for the array or count is greater than the number of elements from index to the end of the source collection.
public static bool TF(bool tf, string filepath, string output)
{
long _chunk = 16 * 1024; //buffer count
long total_size = 0
long rdlen = 0;
long wrlen = 0;
long full_chunks = 0;
long end_remain_buf_len = 0;
FileInfo fi = new FileInfo(filepath);
total_size = fi.Length;
full_chunks = total_size / _chunk;
end_remain_buf_len = total_size % _chunk;
fi = null;
FileStream fs = new FileStream(filepath, FileMode.Open);
FileStream fw = new FileStream(output, FileMode.Create);
for (long chunk_pass = 0; chunk_pass < full_chunks; chunk_pass++)
{
int chunk = (int)_chunk * ((tf) ? (1 / 3) : 3); //buffer count for xbuffer
byte[] buffer = new byte[_chunk];
byte[] xbuffer = new byte[(buffer.Length * ((tf) ? (1 / 3) : 3))];
//Read chunk of file into buffer
fs.Read(buffer, (int)rdlen, (int)_chunk); //ERROR occurs here
//xbuffer = do stuff to make it *3 longer or *(1/3) shorter;
//Write xbuffer into chunk of completed file
fw.Write(xbuffer, (int)wrlen, chunk);
//Keep track of location in file, for index/offset
rdlen += _chunk;
wrlen += chunk;
}
if (end_remain_buf_len > 0)
{
byte[] buffer = new byte[end_remain_buf_len];
byte[] xbuffer = new byte[(buffer.Length * ((tf) ? (1 / 3) : 3))];
fs.Read(buffer, (int)rdlen, (int)end_remain_buf_len); //error here too
//xbuffer = do stuff to make it *3 longer or *(1/3) shorter;
fw.Write(xbuffer, (int)wrlen, (int)end_remain_buf_len * ((tf) ? (1 / 3) : 3));
rdlen += end_remain_buf_len;
wrlen += chunk;
}
//Close opened files
fs.Close();
fw.Close();
return false; //no functionality yet lol
}
答案 0 :(得分:5)
Read()
的{{1}}方法(Stream
的基类)返回一个FileStream
,表示读取的字节数,0表示没有更多的字节数阅读,所以你甚至不需要事先知道文件大小:
int
如果您可以让框架决定块大小,那么甚至public static void CopyFileChunked(int chunkSize, string filepath, string output)
{
byte[] chunk = new byte[chunkSize];
using (FileStream reader = new FileStream(filepath, FileMode.Open))
using (FileStream writer = new FileStream(output, FileMode.Create))
{
int bytes;
while ((bytes = reader.Read(chunk , 0, chunkSize)) > 0)
{
writer.Write(chunk, 0, bytes);
}
}
}
也可以解决问题。
答案 1 :(得分:2)
我认为这条线路失败了:
fw.Write(xbuffer, (int)wrlen, chunk);
您将xbuffer声明为
byte[] xbuffer = new byte[(buffer.Length * ((tf) ? (1 / 3) : 3))];
由于1 / 3
是一个整数除法,它返回0.并且你声明xbuffer
的大小为0因此错误。您可以通过将其中一个操作数转换为浮点类型来修复它或者使用literals.But然后你仍然需要将结果强制转换为整数。
byte[] xbuffer = new byte[(int)(buffer.Length * ((tf) ? (1m / 3) : 3))];
同样的问题也出现在chunk
声明中。