HiveBrain v1.2.0
Get Started
← Back to all entries
snippetcsharpCritical

Best way to read a large file into a byte array in C#?

Submitted by: @import:stackoverflow-api··
0
Viewed 0 times
arraybytebestfilewaylargeintoread

Problem

I have a web server which will read large binary files (several megabytes) into byte arrays. The server could be reading several files at the same time (different page requests), so I am looking for the most optimized way for doing this without taxing the CPU too much. Is the code below good enough?

public byte[] FileToByteArray(string fileName)
{
    byte[] buff = null;
    FileStream fs = new FileStream(fileName, 
                                   FileMode.Open, 
                                   FileAccess.Read);
    BinaryReader br = new BinaryReader(fs);
    long numBytes = new FileInfo(fileName).Length;
    buff = br.ReadBytes((int) numBytes);
    return buff;
}

Solution

Simply replace the whole thing with:

return File.ReadAllBytes(fileName);


However, if you are concerned about the memory consumption, you should not read the whole file into memory all at once at all. You should do that in chunks.

Code Snippets

return File.ReadAllBytes(fileName);

Context

Stack Overflow Q#2030847, score: 941

Revisions (0)

No revisions yet.