在WHILE循环中处理C#filestream输入导致执行时间错误
我正在尝试创建一个C#控制台应用程序,它处理给定目录中的所有文件,并将输出写入另一个给定目录。我想一次处理X字节的输入文件在WHILE循环中处理C#filestream输入导致执行时间错误,c#,.net,filestream,C#,.net,Filestream,我正在尝试创建一个C#控制台应用程序,它处理给定目录中的所有文件,并将输出写入另一个给定目录。我想一次处理X字节的输入文件 namespace FileConverter { class Program { static void Main(string[] args) { string srcFolder = args[0]; string destFolder = args[1];
namespace FileConverter
{
class Program
{
static void Main(string[] args)
{
string srcFolder = args[0];
string destFolder = args[1];
string[] srcFiles = Directory.GetFiles(srcFolder);
for (int s = 0; s < srcFiles.Length; s++)
{
byte[] fileBuffer;
int numBytesRead = 0;
int readBuffer = 10000;
FileStream srcStream = new FileStream(srcFiles[s], FileMode.Open, FileAccess.Read);
int fileLength = (int)srcStream.Length;
string destFile = destFolder + "\\" + Path.GetFileName(srcFiles[s]) + "-processed";
FileStream destStream = new FileStream(destFile, FileMode.OpenOrCreate, FileAccess.Write);
//Read and process the source file by some chunk of bytes at a time
while (numBytesRead < fileLength)
{
fileBuffer = new byte[readBuffer];
//Read some bytes into the fileBuffer
//TODO: This doesn't work on subsequent blocks
int n = srcStream.Read(fileBuffer, numBytesRead, readBuffer);
//If we didn't read anything, there's no more to process
if (n == 0)
break;
//Process the fileBuffer
for (int i = 0; i < fileBuffer.Length; i++)
{
//Process each byte in the array here
}
//Write data
destStream.Write(fileBuffer, numBytesRead, readBuffer);
numBytesRead += readBuffer;
}
srcStream.Close();
destStream.Close();
}
}
}
}
我不想将整个文件加载到内存中,因为它可能有很多GB的大小。我真的希望能够读取一定数量的字节,处理它们,将它们写入文件,然后读取下一个X字节并重复
它通过循环的一次迭代,然后在第二次迭代中消亡。我得到的错误是:
“偏移量和长度超出了数组的界限,或者计数大于从索引到源集合结尾的元素数。”
我使用的示例文件大约是32k
有人能告诉我这里做错了什么吗?要读取的第二个参数不是文件中的偏移量,而是开始写入数据的缓冲区中的偏移量。所以只要通过0 另外,不要假设每次都填充了缓冲区:您应该只处理缓冲区中的“n”字节。在迭代之间应该重用缓冲区 如果需要准确地读取一定数量的字节,请执行以下操作:
static void ReadOrThrow(Stream source, byte[] buffer, int count) {
int read, offset = 0;
while(count > 0 && (read = source.Read(buffer, offset, count)) > 0) {
offset += read;
count -= read;
}
if(count != 0) throw new EndOfStreamException();
}
请注意,Write的工作原理类似,因此需要将0作为偏移量传递,将n作为计数传递。应该是
destStream.Write(fileBuffer, numBytesRead, n);
numBytesRead += n;
因为
n
是读取的实际字节数错误在于“偏移量和长度超出了数组的界限,或者计数大于从索引到源集合末尾的元素数”。在第二次迭代中,numbytes等于readBuffer,即超出您分配的缓冲区末尾的点。好的,我现在看到了如何解释偏移量的问题。你的解释确实澄清了问题。非常感谢。Marc,看看这个代码:如果你传输一个文件,另一方(接收者)怎么知道它接收了所有100%的字节?@RoyiNamir在问题中,这是一个文件流
,所以这个问题不适用。在套接字的情况下,是的-您可能想要实现一些基本的帧/握手协议,在收到有效负载后提供某种确认。
destStream.Write(fileBuffer, numBytesRead, n);
numBytesRead += n;