C# verbatim string literal not working. Very Stran

2019-01-28 09:10发布

问题:

I've tried for quite a long time to figure out whats going on but I've not found anything anywhere that someone besides me has ran into this issue.

I'm simply trying to hard code a path into a string. Easy stuff. Well for some reason

string fullPathSourceFile = @"c:\SQLSOURCE.txt";

is evaluating to c:\\SQLSOURCE.txt

I've tried everything to evaluated it to a single backslash remove the double quotes and it wont work. I even tried Replace(@"\\", @"\") and it has no affect. Anyone have any idea what's going on with my code that would force a double backslash when a single one should be evaluated? This is driving me nuts and it's so damn easy yet causing me a lot of frustration.

I'm then using the string variable below:

                using (StreamReader reader = new StreamReader(fullPathSourceFile))
                {
                    string line;

                    while ((line = reader.ReadLine()) != null)
                    {
                        sqlDBsource = line.ToString();
                    }

                    reader.Close();
                }

Thanks to everyone for their input which helped my figure out what I was doing wrong. In Visual Studio (which is confusing) when you look at the value of a string in the debugger, it puts escapes in for you, so a double-backslash in a watch window or variable value popup is normal and does not mean there are actually two backslashes. When you mouse-over the variable or watch it in the watch window, click the magnifying glass icon at the right hand side of the tooltip/pane, this will show you the unescaped string at it would be printed to the console. Another way to display the actual results is: Console.WriteLine(the_problem_string); The issue I was having with the code is outside the scope of the post but the confusion of the results I was seeing from Visual Studio lead me to believe the string was the source of the problem when it wasn't.

回答1:

This was a weird one. So I removed the verbatim as suggested in the comments and it worked when I used the double backslashes in the string. For some reason the code did not like the verbatim string and was translating the backslashes incorrectly. This resolved the issue. If anyone runs in to this you may need to play with the verbatim/non-verbatim strings because in some circumstances the compiler prefers non-verbatim.