Saturday, April 6, 2013

Add new line in .resx resource string

A simple topic. When adding newline such as \n or \r\n in .RESX resource string, Visual Studio actually escapes the backslash character, so the actual data that is saved is double backslash (\\) instead od single backslash. For example, for input "\n" in .RESX resource editor, the actual data will be \\n  in .resx.

So if one tries to display that resource string in, say, message box, the 2 characters "\n" will be displayed instead of new line which one expects.

For example, let's say ErrorMsg in Resource1.resx has some error message like "Error : invalid data.\n{0}."

msg = string.Format(Resource1.ErrorMsg, errInfo);
MessageBox.Show(this, msg, "Error");

The code above will display something like "Error : invalid data.\nwrong chars found" in one line.
To add new line between two sentence, double backslash should be replaced by single backslash or Environment.NewLine.

msg = string.Format(Resource1.ErrorMsg, errInfo);
msg = msg.Replace("\\n", Environment.NewLine);
MessageBox.Show(this, msg, "Error");

No comments:

Post a Comment