简体   繁体   English

发布读取文件到字节数组

[英]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: 然后将这个字节数组输出为Base64字符串:

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. 我们偶尔会看到的问题是输出只是一个字符串A,例如“ AAAAAAAAAAAAAAAAAAAAAAAAA”,但更长。 I've figured out that if you output a byte array that has been initialized to a given length but not assigned a value (ie 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. 我发现,如果您输出已初始化为给定长度但未分配值的字节数组(即每个字节仍为初始值0),它将在Ba​​se64中输出为一系列A。假设是按照文件大小创建了字节数组,但是没有分配每个字节的值。 Looking at the code I can't see any obvious issues with it though, so if anyone knows better I'd be very grateful. 查看代码后,我看不到任何明显的问题,因此,如果有人知道的更好,我将不胜感激。

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. 为了后代,我确实将其更改为File.ReadAllBytes ,但是我还发现问题出在文件本身,并且空字节数组实际上是正确的。 Ie each byte was still the initial value of 0, so a corresponding base64 string of "A"s was also correct. 也就是说,每个字节仍然是初始值0,因此相应的base64字符串“ A”也是正确的。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM