Search code examples
c#winformslistviewbinarywriter

GetByteCount shows up negative, but it's not


so i am trying to get ByteCount from a litview subitem, but it always shows up negative error: [Argument OutOfRangeException was unhandled: 'count' mustn't be negative, Parameter name: count] this is the code line i get the error on:

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

i tried this:

 if (enc.GetByteCount(listView1.Items[i].SubItems[3].Text) > 0)
                {
                    bw.Write(enc.GetBytes(listView1.Items[i].SubItems[3].Text + (new string('\0',dbytecnt - enc.GetByteCount(listView1.Items[i].SubItems[3].Text)))));
                }

does not work, and even made the if condition to be '> -1', same result.


Solution

  • The exception is an ArgumentOutOfRangeException on parameter count. It's probably the string constructor which throws this exception, not GetByteCount.

    It means that the result of the subtraction dbytecnt - enc.GetByteCount(listView1.Items[i].SubItems[3].Text) is negative.

    Try this:

    if (dbytecnt - enc.GetByteCount(listView1.Items[i].SubItems[3].Text) > 0)
    {
        bw.Write(enc.GetBytes(listView1.Items[i].SubItems[3].Text + (new string('\0',dbytecnt - enc.GetByteCount(listView1.Items[i].SubItems[3].Text)))));
    }