2

I am trying to write and read a binary file using c# BinaryWriter and BinaryReader classes. When I am storing a string in file, it is storing it properly, but when I am trying to read it is returning a string which has '\0' character on every alternate place within the string.

Here is the code:

 public void writeBinary(BinaryWriter bw)
 {
     bw.Write("Hello");
 }

 public void readBinary(BinaryReader br)
 {
     BinaryReader br = new BinaryReader(fs);
     String s;
     s = br.ReadString();
  }

Here s is getting value as = "H\0e\0l\0l\0o\0".

2

1 Answer 1

5

You are using different encodings when reading and writing the file.

You are using UTF-16 when writing the file, so each character ends up as a 16 bit character code, i.e. two bytes.

You are using UTF-8 or some of the 8-bit encodings when reading the file, so each byte will end up as one character.

Pick one encoding and use for both reading and writing the file.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.