How to Calculate String Length in Bytes?

  • Thread starter Thread starter PJ Olson
  • Start date Start date
P

PJ Olson

I have a string that I am writing to a binary file. I am trying to determine
the size of the string in bytes as it will be stored in the file.

Currently, the string is 19 characters in length so I am using the following
calculation to get the right size:

(timestamp.length * 2) - 14

But, the string could be variable size which will mess up my the
calculation. Is there a function that does this?

Thanks,
PJ
 
First convert string to byte[] and then byte.length.

For more info see System.Text.Encoding - this provides methods to convert
string to bytes.
 
Ivar said:
First convert string to byte[] and then byte.length.

For more info see System.Text.Encoding - this provides methods to convert
string to bytes.

You don't need to actually convert it first - you can use
Encoding.GetByteCount.
 
Back
Top