StreamReader and binary data

走远了吗. 提交于 2019-12-07 03:32:23

问题


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.


回答1:


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

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




回答2:


use BinaryReader



来源:https://stackoverflow.com/questions/6491305/streamreader-and-binary-data

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!