The Microsoft website has the code snippet:
using (FileStream fsSource = new FileStream(pathSource, FileMode.Open, FileAccess.Read)) { // Read the source file into a byte array. byte[] bytes = new byte[fsSource.Length]; int numBytesToRead = (int)fsSource.Length; int numBytesRead = 0; while (numBytesToRead > 0) { // Read may return anything from 0 to numBytesToRead. int n = fsSource.Read(bytes, numBytesRead, numBytesToRead); // Break when the end of the file is reached. if (n == 0) break; numBytesRead += n; numBytesToRead -= n; } } What concerns me is that fsSource.Length is a long, whereas numBytesRead is an int so at most only 2 * int.MaxValue can be read into bytes (the head and the tail of the stream). So my questions are:
- Is there some reason that this is OK?
- If not, how should you read a
FileStreaminto abyte[].
int.MaxValueis 2GB. If you haven't already given special consideration to the fact that you are proposing to load more than 4GB of data into memory all at once, please do so now.int.MaxValuebytes in there however you read it. (Other platforms, like Mono, might not have that restriction.)