Question

Today I found out that putting strings in a resource file will cause them to be treated as literals, i.e putting "Text for first line \n Text for second line" will cause the escape character itself to become escaped, and so what's stored is "Text for first line \n Text for second line" - and then these come out in the display, instead of my carriage returns and tabs

So what I'd like to do is use string.replace to turn \\ into \ - this doesn't seem to work.

s.Replace("\\\\", "\\"); 

doesn't change the string at all because the string thinks there's only 1 backslash

s.Replace("\\", "");

replaces all the double quotes and leaves me with just n instead of \n

also, using @ and half as many \ chars or the Regex.Replace method give the same result

anyone know of a good way to do this without looping through character by character?

Was it helpful?

Solution

Since \n is actually a single character, you cannot acheive this by simply replacing the backslashes in the string. You will need to replace each pair of \ and the following character with the escaped character, like:

s.Replace("\\n", "\n");
s.Replace("\\t", "\t");
etc

OTHER TIPS

You'd be better served adjusting the resx files themselves. Line breaks can be entered via two mechanisms: You can edit the resx file as XML (right-click in Solution Explorer, choose "Open As," and choose XML), or you can do it in the designer.

If you do it in the XML, simply hit Enter, backspace to the beginning of the newline you've created, and you're done. You could do this with Search and Replace, as well, though it will be tricky.

If you use the GUI resx editor, holding down SHIFT while pressing ENTER will give you a line break.

You could do the run-time replacement thing, but as you are discovering, it's tricky to get going -- and in my mind constitutes a code smell. (You can also make a performance argument, but that would depend on how often string resources are called and the scale of your app in general.)

I'm actually going with John's solution and editing the XML directly as that's the better solution for the project, but codelogic answered the question that was driving me insane.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top