How to Convert a C# String Value to an Escaped String Literal

Can I convert a C# string value to an escaped string literal?

There's a method for this in Roslyn's Microsoft.CodeAnalysis.CSharp package on NuGet:

private static string ToLiteral(string valueTextForCompiler)
{
return Microsoft.CodeAnalysis.CSharp.SymbolDisplay.FormatLiteral(valueTextForCompiler, false);
}

Obviously, this didn't exist at the time of the original question, but it might help people who end up here from Google Search.

Convert a C# string value to an escaped string literal with Roslyn

You can create a SyntaxNode (LiteralExpressionSyntax) from the input string and than take the string representation of the created node:

public static string ToLiteral(this string input)
{
return SyntaxFactory.LiteralExpression(SyntaxKind.StringLiteralExpression, SyntaxFactory.Literal(input)).ToFullString();
}

How to convert a string containing escape characters to a string

If you are looking to replace all escaped character codes, not only the code for @, you can use this snippet of code to do the conversion:

public static string UnescapeCodes(string src) {
var rx = new Regex("\\\\([0-9A-Fa-f]+)");
var res = new StringBuilder();
var pos = 0;
foreach (Match m in rx.Matches(src)) {
res.Append(src.Substring(pos, m.Index - pos));
pos = m.Index + m.Length;
res.Append((char)Convert.ToInt32(m.Groups[1].ToString(), 16));
}
res.Append(src.Substring(pos));
return res.ToString();
}

The code relies on a regular expression to find all sequences of hex digits, converting them to int, and casting the resultant value to a char.

C# Convert Escape Characters inside string variable into string literal for SQL query

Your problem is not caused by the escaped characters. Those only matter to C#. When the string is concatenated to your sql query, they will just be a regular carriage return and linefeed.

The real problem is caused by using string concatenation in the first place! You have an apostrophe in your data that will mess up the final query once it is concatenated.

Instead, use a parameterized query and this will not be a problem and you will avoid the sql injection vulnerability too!

// Here is the value of the string which IS NOT actually a verbatim string literal, but a value passed on from a selected dropdown list.
strEmailText = "We're writing in regard to XXX mentioned above.\r\nPlease contact us.\r\nWe're available by direct reply.\r\nThank you for your assistance."

// Here I create the actual SQL string for use to query the database
strSQL = @"SELECT DISTINCT TBL_EmailText.ID FROM TBL_EmailText WHERE TBL_EmailText.Text = @EmailText";

using (var sqlCmd = new SqlCommand(strSQL, conn))
{
sqlCmd.CommandType = CommandType.Text;
sqlCmd.Parameters.Add(new SqlParameter { ParameterName = "@EmailText", SqlDbType = SqlDbType.NVarChar, Value = strEmailText });

using(SqlDataReader rdr = sqlCmd.ExecuteReader())
{
//Do something with the data
}
}

Note the use of the parameter @EmailText in the sql query and how it is added to the Parameters collection of the sqlCmd object.

This approach will eliminate the problem with apostrophes in the query and, more importantly, the sql injection vulnerability.

Escape double quotes in a string

No.

Either use verbatim string literals as you have, or escape the " using backslash.

string test = "He said to me, \"Hello World\" . How are you?";

The string has not changed in either case - there is a single escaped " in it. This is just a way to tell C# that the character is part of the string and not a string terminator.



Related Topics



Leave a reply



Submit