Vahid
Vahid

Reputation: 5444

The correct way to create Binary files in C#

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.

Upvotes: 1

Views: 3209

Answers (1)

Dai
Dai

Reputation: 155250

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.

Upvotes: 3

Related Questions