FileStream Read/Write method's limitation

jams picture jams · Apr 13, 2011 · Viewed 16.8k times · Source

FileStream's read/write method can take only integer value as length. But FileStreamobject returns length in long. In this case, what if file size is larger than integer value (approximate more than 2GB). Then how FileStream's read/write method handle long value.

Answer

Jon Skeet picture Jon Skeet · Apr 13, 2011

Then you read and write in multiple chunks. The CLR has a limit on the size of any particular object anyway (also around 2GB IIRC, even on a 64-bit CLR), so you couldn't have a byte array big enough for it to be a problem.

You should always loop when reading anyway, as you can't guarantee that a Read call will read as many bytes as you requested, even if there's more data to come.

EDIT: Reading in chunks:

byte[] buffer = new byte[1024 * 32];
int bytesRead;

while ((bytesRead = stream.Read(buffer, 0, buffer.Length)) > 0)
{
    // Use the data you've read
}

Writing in chunks will depend on what you're writing... it's hard to talk about it in the abstract.