Search code examples
c#winformsbinarywriter

Write empty bytes using binarywriter


so i am using binarywriter to write some strings over the original strings, but i need to overwrite the whole string in the binary file, so i am trying to write the new string, and overwrite the rest of the old string with 0x00 (empty bytes), this is what i tried, but not working:

bw.Write(enc.GetBytes(listView1.Items[i].SubItems[2].Text + (31 - enc.GetByteCount(listView1.Items[i].SubItems[2].Text)) * '\0'));

31 is the constant int that all old strings can't tresspass (don't ask me, it's a script thingy)


Solution

  • That's because:

    number * '\0'
    = number * 0  ('\0' converted to int)
    => always equal to 0
    

    To generate a string filled with \0 (or any char) of a certain length, use:

    new string(`\0`, number)
    

    In your case:

    string newStr = listView1.Items[i].SubItems[2].Text;
    bw.Write(enc.GetBytes(newStr + new string('\0', (31 - enc.GetByteCount(newStr)))));