Click here to Skip to main content
15,886,799 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
Howdy, I intend to write char to a binary file with binarywriter in C#:


FileStream filestream = new FileStream("test.t", FileMode.Create, FileAccess.Write, FileShare.Read, 1024);
      BinaryWriter binaryWriter = new BinaryWriter(filestream);
      binaryWriter.Write("hello");
      binaryWriter.Write("AAA");
      binaryWriter.Close();
      file.Close();


But when I exam the output file I found there are extra bytes in the front of each string, such that the hello become six chars: 0x05 'h''e''l''l''o' and "AAA" become four chars: 0x03'A''A''A'

Anyone know why?



VS 2008
Test in win7 and xp.
Posted
Updated 1-May-11 7:14am
v3

Yes.

Simple: the prefix is the lengths. If you try with the code you actually wrote here, (and fix the compilation error - it should be "filestream.Close()" - you will find that the file contains
0x05  - number of characters in the string "hello"
'h'
'e'
'l'
'l'
'o'
0x03  - number of characters in the string "AAA"
'A'
'A'
'A'
The version of this in your application had a string of ten characters to start with, rather than five
 
Share this answer
 
Comments
Du Sijun 1-May-11 13:18pm    
Yes, it ought to be 0x05
Sergey Alexandrovich Kryukov 1-May-11 18:17pm    
You know how string works, nice of you to tell to those how don't... :-) My 5.
--SA
Strings are preceded by a length byte as described here[^]. It's always best to read the documentation first.
 
Share this answer
 
Comments
Sergey Alexandrovich Kryukov 1-May-11 18:17pm    
You know that, too... :-) My 5.
--SA
If you don't want or need the length byte you can call Write with a Char [] array instead of a String.
 
Share this answer
 

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900