在.NET中反序列化以null结尾的字符串的最佳方法是什么?

时间:2021-11-05 20:40:44

I am reading a message from my network connection which is serialized as a series of null-terminated strings (and other binary data)

我正在从我的网络连接中读取一条消息,该消息被序列化为一系列以空字符结尾的字符串(以及其他二进制数据)

I could read a char at a time using a BinaryReader, until I find a NULL.

我可以使用BinaryReader一次读取一个char,直到找到NULL。

Is there a more efficient way that is still simple? I'm expecting strings less than 64 chars in length, but they could be longer.

还有一种更简单的更有效的方法吗?我期待长度小于64个字符的字符串,但它们可能会更长。

2 个解决方案

#1


I think reading byte by byte is a reasonable option, but I would use a BufferedStream to minimize IO on the underlying stream.

我认为逐字节读取是一个合理的选择,但我会使用BufferedStream来最小化底层流上的IO。

#2


Read the whole thing into a string, then use String.Split to split on the nulls.

将整个事物读入字符串,然后使用String.Split拆分空值。

Remember that strings are not null-terminated in .NET.

请记住,字符串在.NET中不以空值终止。

#1


I think reading byte by byte is a reasonable option, but I would use a BufferedStream to minimize IO on the underlying stream.

我认为逐字节读取是一个合理的选择,但我会使用BufferedStream来最小化底层流上的IO。

#2


Read the whole thing into a string, then use String.Split to split on the nulls.

将整个事物读入字符串,然后使用String.Split拆分空值。

Remember that strings are not null-terminated in .NET.

请记住,字符串在.NET中不以空值终止。