c# - 如何在不使用空字节填充数组的情况下将文件中的字节序列写入字节数组?
问题描述
我有
[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();
}
但是,如果您坚持通过缓冲区,则当您到达文件末尾时,您无法避免部分缓冲区为空(具有空字节),但这就是返回值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
推荐阅读
- windows - 使用 libcurl 连接到 IMAP 服务器
- machine-learning - sklearn 和 weka kNN 预测除了一个数据点外,其他所有预测都完全相同
- string - TypeScript中基于字符串内容的重载函数
- javascript - 将 Bootstrap 合并到 Webpack 配置中时出现错误
- java - JDBC API 和 PostgreSQL 驱动程序有什么区别?
- json - jq:如何在嵌套数组中进行选择
- vhdl - 存储在变量内部(if 语句)中的条件评估给出正确的结果,而直接评估(断言)给出错误的结果
- c# - 为 RESTful WCF C# 构造 XML 请求
- c++ - 将 2D 内存分配转换为 1D 矢量的最佳方法
- python - 尝试在 python 中编码文本时出错