简体   繁体   中英

C# read and write a file with a given buffer length and cut overflow

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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