Search code examples
c#arraysiofilestream

Issue reading file to byte array


I'm maintaining a program that has the following code to read a file to a byte array:

using (FileStream fileStream = new FileStream(filePath, FileMode.Open))
{
    fileStream.Position = 0;

    int fileSize = (int)fileStream.Length;
    int readSize;
    int remain = fileSize;
    var pos = 0;

    byteData = new byte[fileSize];

    while (remain > 0)
    {
        readSize = fileStream.Read(byteData, pos, Math.Min(1024, remain));
        pos += readSize;
        remain -= readSize;
    }
}

And then afterwards outputs this byte array as a Base64 string:

var value = "File contents:" + Environment.NewLine + Convert.ToBase64String(byteData)

The issue we are occasionally seeing is that the output is just a string of A's, like "AAAAAAAAAAAAAAAAAAAAAA", but longer. I've figured out that if you output a byte array that has been initialized to a given length but not assigned a value (i.e. each byte is still the initial value of 0) it will output in Base64 as a series of A's, so my hypothesis is that the byte array is being created to the size of the file, but then the value of each byte isn't being assigned. Looking at the code I can't see any obvious issues with it though, so if anyone knows better I'd be very grateful.


Solution

  • For posterity, I did end up changing it to File.ReadAllBytes, however I also found out that the issue was with the file itself, and an empty byte array was actually correct. I.e. each byte was still the initial value of 0, so a corresponding base64 string of "A"s was also correct.