RichTextBox does not display full contents of a file or string if Chr(0) (Null Character) is found

There are a lot of instances where you may end up using a RichTextBox on a form because of it’s ability to handle and display large amounts of data but you won’t actually want or need to use any of the rich text features it. Recently, I ran into an instance where when I set the Text property, not all of my string was being displayed. In my case, the string was the contents of a text file. I tried reading it in both through My.Computer.FileSystem.ReadAllText and also manually creating a StreamReader and building the contents myself. Each time, the contents of my string did not match what ended up in the RichTextBox.

I opened up my Hex Editor, went to the portion of the file where the RichTextBox stopped display text and I found that there was a null character in the file. I suspect the RichTextBox saw this as an EOF (end of file) marker and stopped displaying text. How did my files get that character? They’re created programmatically and retrieve environment text from difference services and applications. My solution was, strip out the null characters before setting the RichTextBox text. After doing this, all of the text displays fine. In VB you can do it easily like this (ignore that I’m not setting an encoding, this is just a demonstration and also assume that the loadFile string points to a valid file on your workstation):

Dim buf As String = My.Computer.FileSystem.ReadAllText(loadFile)
buf = buf.Replace(Chr(0), "")

Leave a comment

Please note that we won't show your email to others, or use it for sending unwanted emails. We will only use it to render your Gravatar image and to validate you as a real person.