Tuesday, February 15, 2005

StringBuilder.ToString with Null Characters (0x00)

A little interesting find in todays coding. I am parsing a binary file type and when I encounter values that I don't want to convert, I was setting them to 0 (ASCII Null). These values were then added to a StringBuilder object successfully. The interesting thing is when I finish the operation and return a StringBuilder.ToString, the text is truncated at the Null character position even though there is additional text beyond it. I was unable to find a quick and easy way to erase the text I didn't want to see in the ouput so I ended up changing the offending characters to 32 (ASCII Space). I found an article on Expert Exchange (great site) about a similar problem but didn't find a specific solution doing it the way I am. Technically, I could create another array and populate it and then return the new array but it seems less efficient then just setting the values to 0 and letting a conversion remove them. I guess this was the intended method of .NET (NUL signals the end of the string). Feedback is welcome on this :)

No comments:

Post a Comment