How BinaryWriter in c# saves its content?

1.1k views Asked by At

created a binary file by using c#: The code I used was this

     try            
         {
            Console.WriteLine("Binary Writer");

       using (BinaryWriter b = new BinaryWriter(File.Open("C:\\file.bin",FileMode.Create)))
            {  
                b.Write("world");
                b.Write("god");
                b.Write("its cool");
                b.Write("1000");
                b.Flush();
            }

        }
        catch (IOException ioexp)
        {
            Console.WriteLine("Error: {0}", ioexp.Message);
        }
    }

The output file what i see had-

world(SOMETHING HERE)god(SOMETHING HERE)its cool(SOMETHING HERE)1000

Isn'nt it should be something in binary format?

3

There are 3 answers

0
Alberto On

Actually the file is in binary format. Every file is in binary format, the difference between text files and data files is that on text files, each byte will map directly to it's char representation. What are you seeing here instead, is that for each piece of information that you wrote in that file, there is something else that is used to encode that information.

0
Robert Rouhani On

Text isn't magically going to appear different outputted into a binary file. The text is stored with an encoding you specify in your BinaryWriter instance. In your case, since it's not specified, it defaults to UTF-8 according to the MSDN page for BinaryWriter.

The thing you see between each string is the length prefixed to each string as a UTF-7 encoded unsigned integer. Since that number is in "binary" format, it'll show up as the UTF-8 representation of that value.

Try opening the file in a hex editor, you'll see exactly how strings are written by a BinaryWriter.

1
Hans Passant On

Most simple value types are easy to convert to binary. They have a fixed number of bytes that can represent their value. Like a variable of type byte can be written as a single byte. An int can be written as 4 bytes. A decimal can be written as 16 bytes. Etcetera.

But strings are tricky, they can have a variable length. So BinaryWriter must do something extra to ensure that the string can be read back again from the file. Which is the (SOMETHING HERE) that you see in the file. It stores the length of the string. Followed by the characters in the string.

Now it is easy for BinaryReader to read the string back. It first reads the length, then it knows how many characters to read.

Do note that this also means that the file can only be read back with BinaryReader. This tends to be a problem when you write a file that another program is supposed to read. Which does mean that you should never use the Write(string) method. Typically you'd use Write(byte[]) instead. Use the proper Encoding to generate that byte[].