Search code examples
c#winformsbinarywriter

BinaryWrite two empty unicode characters after a string


so i am trying to add two of 0x00 after every string i write in a binary file, these are what i tried(1 try per line), but i always end up having only one 0x00 after each string:

bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + '\0' + '\0'));
bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + "\0"));
bw.Write(enc.GetBytes(listView1.Items[i].SubItems[1].Text + (new string('\0', 2))));

but they all end up with the same result, is there another Unicode escape i can try to use ? or am i doing anything wrong in these lines ? and for an aside note, String enc = Encoding.Unicode


Solution

  • What you are doing should work. This test code demonstrates:

    string test = "X" + '\0' + '\0';
    Console.WriteLine(test.Length); // Prints 3
    var bytes = Encoding.Unicode.GetBytes(test);
    Console.WriteLine(bytes.Length); // Prints 6
    

    bytes contains the following byte values: 88, 0, 0, 0, 0, 0 - which is correct.

    So I assume there's something wrong elsewhere with your code.