public static byte[] GetZeroTerminatedBytes(string text, Encoding encoding)
{
if (string.IsNullOrEmpty(text))
return new byte[] { 0 };
// This should be a little less wasteful than simply appending
// a null terminator to the string and then converting it
int byteCount = encoding.GetByteCount(text);
var buffer = new byte[byteCount + 1];
unsafe
{
fixed (byte* bp = buffer)
fixed (char* ch = text)
{
int count = encoding.GetBytes(ch, text.Length, bp, byteCount);
Debug.Assert(count == byteCount);
}
}
// And the end cap...
buffer[buffer.Length - 1] = 0;
return buffer;
}