StreamReader and binary data

I have this text file that contains different fields. Some fields may contain binary data. I need to get all the data in a file, but right now, using StreamReader, then it will not read the block of binary data and the data after that. What would be the best solution to solve this problem?

Example:

field1|field2|some binary data here|field3 

Now I read in the file as follows:

 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 starting and ending positions of binary fields.

+6
source share
2 answers

StreamReader not intended for binary data. It is intended for text data, so it extends TextReader . To read binary data, you should use Stream , and not try to put the results in a string (which is again for text data).

All in all, it is a bad idea to mix binary data and text data in a file like this - what happens if the binary data includes | character for example? You might want to include binary data in some text form, such as the base64 variant, avoiding |.

+7
source
+9
source

Source: https://habr.com/ru/post/891437/


All Articles