Why is String.Format unable to escape characters when the string is in a resource?

var result1 = String.Format("Hello\n\t{0}\n\n", "Bill");
// MyResource.FormatMe contains the same text: Hello\n\t{0}\n\n
var result2 = String.Format(MyResource.FormatMe, "Bill");

      

result1 as expected:

"Hello
    Bill

"

      

result2 not:

Hello\n\tBill\n\n

      

Why is String.Format

n't it escaping the escape characters when the format string comes from a resource?

+3


source to share


1 answer


String.Format

nothing comes out. This compiler that handles \n

, \t

and others the escape-sequence string literals into something else (that is, if you look at the binary code generated by the compiler, and search your line, you will not find literal \

followed n

, but the actual bytes for line break characters). This way, anything that doesn't exist as a string literal in your code won't be processed by escape sequences.

You can easily process your lines to change to \n

and \t

from the actual line breaks and tabs:



string result2_format = MyResource.FormatMe.Replace("\\n", "\n").Replace("\\t", "\t");

      

+1


source







All Articles