Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you get StringBuilder's ToString method to not escape the escape characters in a string?

Thanks to NgM I am using StringBuilder in .NET 3.5 to find and escape special chars. However, when I use the ToString method, it escapes the escape chars which then makes the previous exercise useless. Anyone know how to get around that?

Here is the code:

    private String ParseAndEscapeSpecialChars(String input)
    {
        StringBuilder sBuilder = new StringBuilder(input);
        String output;
        String specialChars = @"([-\]\[<>\?\*\\\""/\|\~\(\)\#/=><+\%&\^\'])";
        Regex expression = new Regex(specialChars);

        if (expression.IsMatch(input))
        {
            sBuilder.Replace(@"\", @"\\");
            sBuilder.Replace(@"'", @"\'");                
        }

        output = sBuilder.ToString();
        return output;
    }

Here are the results from debug:

input       "005 - SomeCompany's/OtherCompany's Support Center"
sBuilder    {005 - SomeCompany\'s/OtherCompany\'s Support Center}
output      "005 - SomeCompany\\'s/OtherCompany\\'s Support Center"
like image 511
mattg Avatar asked Dec 22 '22 10:12

mattg


1 Answers

StringBuilder doesn't escape characters. It does nothing special or clever. Dollars to doughnuts you're just seeing this in the debugger, which does show you an escaped version.

like image 188
Jon Skeet Avatar answered Jan 05 '23 00:01

Jon Skeet