Click here to Skip to main content
11,720,557 members (78,443 online)
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 1:00am
Du Sijun1.1K
Edited 1-May-11 7: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 Sergey Alexandrovich Kryukov 2,129
1 OriginalGriff 884
2 F-ES Sitecore 640
3 Maciej Los 609
4 Richard MacCutchan 540


Advertise | Privacy | Mobile
Web04 | 2.8.150901.1 | Last Updated 6 Sep 2012
Copyright © CodeProject, 1999-2015
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