I am creating a binary file, for this I am using
namespace BinaryStream
{
class Program
{
static void Main(string[] args)
{
string filename = @"c:\happybirthday.txt";
using (BinaryWriter binWriter =
new BinaryWriter(File.Open(filename, FileMode.Create)))
{
string name = "Sachin";
string wishes = "happy birthday";
binWriter.Write(name.ToCharArray());
binWriter.Write(wishes.ToCharArray());
}
}
}
}
if binWriter.Writer(name) is used the file contains some special characters. But if i convert the string to chararray and write to file , the file contains the normal text(without any special characters).
What is the reason behind this?
The
Write(string)overload is length prefixed:From here: http://msdn.microsoft.com/en-us/library/yzxa6408.aspx
Whereas
Write(char[])is not. That extra information will show up as weird data when opened with text viewing.The reason for this is obvious when looking at read behaviour.
BinaryReader.ReadCharsneeds to be told how many chars to read, whileBinaryReader.ReadStringworks it out by looking at the length prefix.Edit: Possible duplicate, extra info anyway: Difference in writing string vs. char array with System.IO.BinaryWriter