I red: How many bytes will a string take up? and How to know the size of the string in bytes? and some others but I can't figure out the exact count of bytes that a string will take into memory using a BinaryWriter over a MemoryMappedViewStream over a MemoryMappedFile.
Sometimes the lenght taken is the string lenght + 1, sometimes it is the string lenght + 2 ???
I tried both:
- System.Text.ASCIIEncoding.Default.GetByteCount(str)
- System.Text.ASCIIEncoding.Unicode.GetByteCount(str)
But none of them works. I tried the string lenght plus a fixed amount but it does not works either.
If I check the difference between the BinaryWriter.BaseStream.Position before and after, then I can't figure out a way to determine what will be exact amount of bytes written for a string (position after - position before). It sounds like there is alignment or something else I can't figure out?
How to have the proper amount of bytes to write each time?
Update
I now use Encoding.UTF8.GetByteCount(str) + 1;
, which give me almost the right size most of the time but not always.