Working with Null Characters in C# / .Net

Sat, Dec 20, 2008

Tech Tips

Here is one method to manipulate Null characters in C#:

To Search a String for a Null character:

mystring.Contains(Convert.ToChar(0x0).ToString() );
//The hexidecimal 0x0 is the null character

To Replace all Null Characters in a String:

mystring.Replace(Convert.ToChar(0x0).ToString(), "");

Why Do I Need This?
It might help. I needed it when I got a nasty error message in a data layer that was using web services and soap to retrieve the data:
“There is an error in XML document hexadecimal value 0x00, is an invalid character”
Basically what happened is that a null character was pasted into a SQL Server database via an Access front end. When my app was pulling the data via a SOAP data layer, the null character can not be used in a XML document with UTF encoding. Which is the transport method of this particualr service. So the quick hack was to strip out the null character after the data pull but before the soap transfer back to the client.

Bookmark and Share

15 Responses to “Working with Null Characters in C# / .Net”

  1. Ashu Says:

    Grt work dude it helped me alot…thanx

  2. George Says:

    I need a conversion of Constants.vbNullChar to a C# method. I’ve tried creating a constant like this:

    private const String vbNullChar = Convert.ToChar(0x0);

    but that gives me an error. Any ideas on how to do this?


  3. George Says:

    … nevermind, I figured it out.. just don’t make it a constant but just declare it like this:

    private String vbNullChar = Convert.ToChar(0).ToString();

  4. Chun Kit Says:

    @George You can also use Microsoft.VisualBasic.Constants.vbNullChar (from Microsoft.VisualBasic.dll).

  5. raul fan Says:

    Thanks a ton! much appreciated

  6. Jason Says:

    (char)0 achieves much the same thing

  7. Pablo Alejandro Perez Acosta Says:

    Thank you very much. It solved the problem we had reading a html files saved as a binary field in Oracle.

  8. bikash Says:

    Char a=Convert.ToChar(0x0) is the correct.
    thank you, It helps me.

  9. Download Templates Says:

    Thanks a lot for sharing this with all people you really recognize what you’re talking about! Bookmarked. Please also visit my site =). We will have a hyperlink trade contract between us

  10. Coralie Says:

    A little rationality lifts the quality of the debate here. Thanks for corntibtiung!

  11. MizardX Says:

    ” is a character literal for the null character.

  12. Calvin Says:

    It’s weird in my case that Replace(”, ‘ ‘) doesn’t work for me. But Trim(”) works find. Luckily in my case there is no null characters in the middle. (My project is a WCF in .NET4, VS2010)