StreamReader的和二进制数据二进制数、StreamReader

2023-09-03 16:48:17 作者:丢了失了魂

我有什么含有不同的领域这个文本文件。某些字段可能包含二进制数据。我需要得到文件中的所有数据,但现在使用的StreamReader那么它不会读取二进制数据块和数据什么来后,当。什么是解决这个问题的最佳解决方案?

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?

例如:

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

编辑:我知道二进制字段的起始和结束位置

I know the start and end positions of the binary fields.

推荐答案

的StreamReader 是不适合二进制数据。它的设计的文本的数据,这就是为什么它扩展了的TextReader 。要读取的二进制数据,你应该使用,而不是试图把结果放到一个字符串(这是再次对文本数据)。

StreamReader isn't designed for binary data. It's designed for text data, which is why it extends TextReader. To read binary data, you should use a Stream, and not try to put the results into a string (which is, again, for text data).

在一般情况下,这是一个坏主意,混合二进制数据和文本数据在这样的文件 - 如果二进制数据包括发生了什么|符号的例子吗?你可能要包括一些文本恩codeD格式的二进制数据,比如一个base64变种避免|。

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 |.

 
精彩推荐
图片推荐