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

前端 未结 4 871
耶瑟儿~
耶瑟儿~ 2020-12-03 13:49
  • I am communicating with a server who needs null terminated string
  • How can I do this smartly in C#?
4条回答
  •  抹茶落季
    2020-12-03 14:41

    I assume you're implementing some kind of binary protocol, if the strings are null terminated. Are you using a BinaryWriter?

    The default BinaryWriter writes strings as length prefixed. You can change that behavior:

    class MyBinaryWriter : BinaryWriter
    {
        private Encoding _encoding = Encoding.Default;
    
        public override void Write(string value)
        {
            byte[] buffer = _encoding.GetBytes(value);
            Write(buffer);
            Write((byte)0);
        }
    }
    

    Then you can just write any string like this:

    using (MyBinaryWriter writer = new MyBinaryWriter(myStream))
    {
        writer.Write("Some string");
    }
    

    You may need to adjust the _encoding bit, depending on your needs.

    You can of course expand the class with specific needs for other data types you might need to transfer, keeping your actual protocol implementation nice and clean. You'll probably also need your own (very similar) BinaryReader.

提交回复
热议问题