Scewbedew wrote:
Suppose I have the following code:
string myFormat = "Line1/nLine 2";
string formattedString = string.Format(myFormat);
...that would produce a 2-line output as expected.
But if I load that very same format string from an xml file:
...load xmlNode WorkNode...
string myFormat= WorkNode.Attributes["text"].InnerText.ToString();
string formattedString = string.Format(myFormat);
...the result is a one-line "Line1/nLine 2" output.
How can I get the string.Format method to handle control characters correctly?
Probably a typo, but you posted "/n" instead of "\n". However, the more
important point is that you misunderstand who is doing what.
string.Format is not resolving \n into a newline character. The
compiler is doing that. In other words, the variable strFormat does not
contain:
L-i-n-e-1-\-n-L-i-n-e-2
In fact, it contains this:
L-i-n-e-1-newline-L-i-n-e-2
because the compiler has already resolved the \n notation into the
corresponding control character. So, string.Format doesn't "handle" the
\n notation at all. It just treats the newline like any other character
and puts it in the output string.
Now, when you read "Line1\nLine2" from an XML file, what you're passing
to string.Format is exactly that sequence of characters:
L-i-n-e-1-\-n-L-i-n-e-2
and so that's what it puts in the output string.
So, the real question is how can you take a character string that may
contain some character escapes, and translate them into the appropriate
control characters. Perhaps someone else can answer that one.