1

I'm using the below code to create a Binary file.

var a = new[]
{
    "C50-12-25",
    "C50-12-20"
};

using (var bw = new BinaryWriter(File.Open("file.bin", FileMode.Create)))
{
    foreach (var i in a)
    {
        bw.Write(i);
    }
}

I opened the file and I'm not seeing something that resembles a picture like this which I always thought a Binary file would look like.

http://www.dotnetperls.com/binary.png

I'm actually able to read the complete text I have written.

C50-12-25   C50-12-20

So is this it? I'm completely new to this so any help to point me in correct direction will be a lot to me.

Vahid
  • 5,144
  • 13
  • 70
  • 146
  • 1
    Another note when opening the file in hex editors: the file content is only valid for the length of the file. E.g. if you write 4 bytes to a file, the first 4 bytes are guaranteed to be correct, but beyond that is garbage. This has something to do with the way files are stored; they simply won't store 4 bytes alone. – kevin Mar 30 '14 at 07:48
  • @kayson A hex-editor would only show garbage beyond the file's length if they read raw from the disk instead of using the operating system's file handling functions. I don't think this is a real concern, I haven't come across a hex-editor like that since Norton Disk Editor. – Dai Mar 30 '14 at 08:19

1 Answers1

3

The overload of Write that you used: BinaryWriter.Write(String), writes out the string you provided to the file using encoding.

It looks like you you want to convert those strings to binary data by decoding them as hexadecimal values... except they don't look like hexadecimal values because they don't come in groups of 2. Anyway, this procedure is documented here ( How can I convert a hex string to a byte array? ).

Note that the "picture" you posted is of a hex editor. You didn't describe in your post how you opened the file; if you open a file in Notepad or a similar editor then you'll always get printed-characters back, not the hexadecimal representation of the file's contents.

Community
  • 1
  • 1
Dai
  • 141,631
  • 28
  • 261
  • 374
  • Thanks Dai, yeah right I made mistake there the image is for a hex file. But my point is if I write anything using these method it can be read into plain text somehow. Am I correct? – Vahid Mar 30 '14 at 07:48
  • @Vahid I think you need a better understanding of what a file really is, and to read-up on encoding and the concept of what a "*view* of data" is. Everything you need to know will be there. – Dai Mar 30 '14 at 08:20