How to split a large file into chunks in c#?

Just call Read repeatedly with a small buffer (I tend to use something like 16K). Note that the call to Read may end up reading a smaller amount than you request. If you’re using a fixed chunk size and need the whole chunk in memory, you could just use an array of that size of course.

Without knowing how you’re sending the file, it’s hard to give much advice about how to structure your code, but it could be something like this:

byte[] chunk = new byte[MaxChunkSize];
while (true)
{
    int index = 0;
    // There are various different ways of structuring this bit of code.
    // Fundamentally we're trying to keep reading in to our chunk until
    // either we reach the end of the stream, or we've read everything we need.
    while (index < chunk.Length)
    {
        int bytesRead = stream.Read(chunk, index, chunk.Length - index);
        if (bytesRead == 0)
        {
            break;
        }
        index += bytesRead;
    }
    if (index != 0) // Our previous chunk may have been the last one
    {
        SendChunk(chunk, index); // index is the number of bytes in the chunk
    }
    if (index != chunk.Length) // We didn't read a full chunk: we're done
    {
        return;
    }
}

If I was more awake I’d probably find a more readable way of writing this, but it’ll do for now. One option is to extract another method from the middle section:

// Attempts to read an entire chunk into the given array; returns the size of
// chunk actually read.
int ReadChunk(Stream stream, byte[] chunk)
{
    int index = 0;
    while (index < chunk.Length)
    {
        int bytesRead = stream.Read(chunk, index, chunk.Length - index);
        if (bytesRead == 0)
        {
            break;
        }
        index += bytesRead;
    }
    return index;
}

Leave a Comment