StreamReader 和二进制数据
我有这个包含不同字段的文本文件。某些字段可能包含二进制数据。我需要获取文件中的所有数据,但现在使用 StreamReader 时,它不会读取二进制数据块以及之后的数据。解决这个问题的最佳解决方案是什么?
示例:
field1|field2|some binary data here|field3
现在我在文件中读取如下内容:
public static string _fileToBuffer(string Filename)
{
if (!File.Exists(Filename)) throw new ArgumentNullException(Filename, "Template file does not exist");
StreamReader reader = new StreamReader(Filename, Encoding.Default, true);
string fileBuffer = reader.ReadToEnd();
reader.Close();
return fileBuffer;
}
编辑:我知道二进制字段的开始和结束位置。
I have this text file what contains different fields. Some fields may contain binary data. I need to get all the data in the file but right now when using StreamReader then it wont read the binary data block and data what comes after that. What would be the best solution to solve this problem?
Example:
field1|field2|some binary data here|field3
Right now i read in the file like this:
public static string _fileToBuffer(string Filename)
{
if (!File.Exists(Filename)) throw new ArgumentNullException(Filename, "Template file does not exist");
StreamReader reader = new StreamReader(Filename, Encoding.Default, true);
string fileBuffer = reader.ReadToEnd();
reader.Close();
return fileBuffer;
}
EDIT: I know the start and end positions of the binary fields.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
使用 BinaryReader
use BinaryReader
StreamReader
不是为二进制数据设计的。它专为文本数据而设计,这就是它扩展TextReader
的原因。要读取二进制数据,您应该使用Stream
,而不是尝试将结果放入字符串中(这同样适用于文本数据)。一般来说,在像这样的文件中混合二进制数据和文本数据是一个坏主意 - 如果二进制数据包含 | 会发生什么?例如符号?您可能希望以某种文本编码形式包含二进制数据,例如避免 | 的 Base64 变体。
StreamReader
isn't designed for binary data. It's designed for text data, which is why it extendsTextReader
. To read binary data, you should use aStream
, and not try to put the results into a string (which is, again, for text data).In general, it's a bad idea to mix binary data and text data in a file like this - what happens if the binary data includes the | symbol for example? You might want to include the binary data in some text-encoded form, such as a base64 variant avoiding |.