Why does BinaryWriter prepend gibberish to the start of a stream? How do you avoid it?

后端 未结 9 1742
别跟我提以往
别跟我提以往 2020-11-30 10:11

I\'m debugging some issues with writing pieces of an object to a file and I\'ve gotten down to the base case of just opening the file and writing \"TEST\" in it. I\'m doing

9条回答
  •  旧巷少年郎
    2020-11-30 10:58

    That's because a BinaryWriter is writing the binary representation of the string, including the length of the string. If you were to write straight data (e.g. byte[], etc.) it won't include that length.

    byte[] text = System.Text.Encoding.Unicode.GetBytes("test");
    FileStream fs = new FileStream("C:\\test.txt", FileMode.Create);
    BinaryWriter writer = new BinaryWriter(fs);
    writer.Write(text);
    writer.Close();
    

    You'll notice that it doesn't include the length. If you're going to be writing textual data using the binary writer, you'll need to convert it first.

提交回复
热议问题