Thursday, May 5, 2011

What is the Best way to deserialize a null-terminated string in .NET?

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.

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.

Thanks

jeff

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

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

    Matthew Flaschen : He didn't say how long the whole message was (or even whether it terminates). There's a good chance reading the whole thing is not feasible.
    ScottS : On the other hand there is not enough info in the question to be sure it is not feasible. It is a good idea that may well help someone else if no the OP.
  • I think reading byte by byte is a reasonable option, but I would use a BufferedStream to minimize IO on the underlying stream.

0 comments:

Post a Comment