首页 > 解决方案 > 如何在不使用空字节填充数组的情况下将文件中的字节序列写入字节数组?

问题描述

我有

[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

标签: c#arraysstreambufferfilestream

解决方案


您在评论中说您只是将字节数组解码为字符串,那么为什么不将文件内容作为字符串读取,例如:

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();
}

但是,如果您坚持通过缓冲区,则当您到达文件末尾时,您无法避免部分缓冲区为空(具有空字节),但这就是返回值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

推荐阅读