How to get a null terminated string from a C# string?

Betamoo picture Betamoo · May 8, 2010 · Viewed 36.4k times · Source
  • I am communicating with a server who needs null terminated string
  • How can I do this smartly in C#?

Answer

Alex McBride picture Alex McBride · May 8, 2010

I think the smart way is to do it simply.

string str = "An example string" + char.MinValue; // Add null terminator.

Then convert it into bytes to send to the server.

byte[] buffer = ASCIIEncoding.ASCII.GetBytes(str);

Of course what encoding you use depends on what encoding the server expects.