如何在不使用空字节填充数组的情况下将文件中的字节序列写入字节数组?

How to write a sequence of bytes from a file to a byte array without padding the array with null bytes?

我有

[13,132,32,75,22,61,50,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0]

我要

[13,132,32,75,22,61,50]

我有一个字节大小为 1048576 的数组,我已使用文件流写入该数组。从这个数组中的特定索引开始,直到数组的末尾都是空字节。数组末尾可能有 100000 个带值的字节和 948576 个空字节。当我不知道文件的大小时如何有效地创建一个大小为 100000 的新数组(即与未知文件中的总字节数相同)并将该文件中的所有字节写入字节数组?

byte[] buffer = new byte[0x100000];
int numRead = await fileStream.ReadAsync(buffer, 0, buffer.length); // byte array is padded with null bytes at the end

你在注释中声明你只是将字节数组解码为字符串,那么为什么不将文件内容作为字符串读取,例如:

var contents = File.ReadAllText(filePath, Encoding.UTF8);
// contents holds all the text in the file at filePath and no more

或者如果您想使用流:

using (var sr = new StreamReader(path)) 
{
    // Read one character at a time:
    var c = sr.Read();

    // Read one line at a time:
    var line = sr.ReadLine();

    // Read the whole file
    var contents = sr.ReadToEnd();
}

但是,如果您坚持要通过缓冲区,则当您到达文件末尾时,您无法避免缓冲区的一部分为空(具有空字节),但这就是 return 值的位置ReadAsync 挽回局面:

byte[] buffer = new byte[0x100000];
int numRead = await fileStream.ReadAsync(buffer, 0, buffer.length);

var sectionToDecode = new byte[numRead];
Array.Copy(buffer, 0, sectionToDecode, 0, numRead);
// Now sectionToDecode has all the bytes that were actually read from the file