i want read a file in 1MB chunks with a FileStream and write it back with another FileStream.
The problem i have, is that the file with ~2.9MB get up to ~3.9MB because the last buffer is to big for the data (so it gets filled with \0 i think).
Is there a way to cut the overflow of the last buffer?
public static void ReadAndWriteFileStreamTest() {
string outputFile = "output.dat";
string inputFile = "input.dat";
using (FileStream fsOut = File.OpenWrite(outputFile))
{
using (FileStream fsIn = File.OpenRead(inputFile))
{
//read in ~1 MB chunks
int bufferLen = 1000000;
byte[] buffer = new byte[bufferLen];
long bytesRead;
do
{
bytesRead = fsIn.Read(buffer, 0, bufferLen);
fsOut.Write(buffer, 0, buffer.Length);
} while (bytesRead != 0);
}
}
}
Any help would be great! :)
PROBLEM:
fsOut.Write(buffer, 0, buffer.Length);
writes all bytes from the buffer, while you read only bytesRead
amount.
SOLUTION:
You should use bytesRead
as third parameter of FileStream.Write - count
- amount of actually read bytes to avoid writing of bytes that aren't actually read.
do
{
bytesRead = fsIn.Read(buffer, 0, buffer.Length);
fsOut.Write(buffer, 0, bytesRead );
} while (bytesRead != 0);