NULL in a string can't copy contents after NUL

2019-09-06 01:35发布

问题:

I have a slight issue when I am getting data back from an external device in bytes and then converting it to a string. I am communicating to this device via a TcpClient.

I receive a message from this external device and format it as a string. The problem I am getting is, the message I get back contains a "NUL". When I try to read its contents the string terminates after it comes across NUL in the string. For example:

hello world NUL blah blah blah

When I add a watcher I don't see blah blah blah in the variable or if I do a normal copy and paste in windows of the whole line (above) it will only copy up to hello world. Its like it is cut off or terminated off the string. Never come across this before.

Perhaps it is the way I reading the byte[] data?

EDIT

https://www.dropbox.com/s/mzr1rvmxiyh4yt3/stack.log

Link to the file (hopefully this is allowed) and the code to read this is:

        StringBuilder str = new StringBuilder();

        using (StreamReader reader = new StreamReader(@"c:\stack.log"))
        {
            str.Append(reader.ReadToEnd());
        }

See the StringBuilder contents doesn't know anything after the NUL character.

Thanks in advance, Onam.

Hope there is enough detail if not I shall add more if required.

回答1:

Search and replace \0 with an empty string or space.



标签: c# string nul