6

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.

hs2d
  • 6,027
  • 24
  • 64
  • 103

2 Answers2

9

use BinaryReader

abatishchev
  • 98,240
  • 88
  • 296
  • 433
7

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

Jon Skeet
  • 1,421,763
  • 867
  • 9,128
  • 9,194
  • @hs2d: So what *does* happen if the binary data includes the ASCII (or whatever encoding is used) representation for `|`? Is there anything in the first two fields which tells you the expected length? – Jon Skeet Jun 27 '11 at 10:13
  • there is nothing what tells me the expected lenght. Look at my other question. Im using template to get the field separators what mark the end of one field: [link](http://stackoverflow.com/questions/6479505/c-template-parsing-and-matching-with-text-file) – hs2d Jun 27 '11 at 10:20
  • ok, got some more information. The binary field is always with the same lenght and i know the start and end positions. I update my original question. – hs2d Jun 27 '11 at 11:05