如何将文件中的字节序列写入字节数组,而不用空字节填充数组?

问题描述 投票:0回答:1

我有

[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# arrays stream buffer filestream
1个回答
1
投票

您在注释中指出,您只是将字节数组解码为字符串,所以为什么不将文件内容读取为字符串,例如:

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
© www.soinside.com 2019 - 2024. All rights reserved.