Click here to Skip to main content
Rate this: bad
good
Please Sign up or sign in to vote.
See more: C# string
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 1-May-11 2:00am
Du Sijun1.1K
Edited 1-May-11 8:14am
v3
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 1

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
  Permalink  
Comments
Du Sijun at 1-May-11 13:18pm
   
Yes, it ought to be 0x05
SAKryukov at 1-May-11 18:17pm
   
You know how string works, nice of you to tell to those how don't... :-) My 5.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 2

Strings are preceded by a length byte as described here[^]. It's always best to read the documentation first.
  Permalink  
Comments
SAKryukov at 1-May-11 18:17pm
   
You know that, too... :-) My 5.
--SA
Rate this: bad
good
Please Sign up or sign in to vote.

Solution 3

If you don't want or need the length byte you can call Write with a Char [] array instead of a String.
  Permalink  

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

  Print Answers RSS
0 OriginalGriff 195
1 ProgramFOX 130
2 Maciej Los 105
3 Sergey Alexandrovich Kryukov 85
4 Afzaal Ahmad Zeeshan 82
0 OriginalGriff 6,564
1 Sergey Alexandrovich Kryukov 6,048
2 DamithSL 5,228
3 Manas Bhardwaj 4,717
4 Maciej Los 4,150


Advertise | Privacy | Mobile
Web03 | 2.8.1411022.1 | Last Updated 6 Sep 2012
Copyright © CodeProject, 1999-2014
All Rights Reserved. Terms of Service
Layout: fixed | fluid

CodeProject, 503-250 Ferrand Drive Toronto Ontario, M3C 3G8 Canada +1 416-849-8900 x 100