web.config backslash appears twice Visual Studio

2020-05-06 10:47发布

问题:

I have an asp.net web application that I made in Visual Studio 2008. Everything worked just fine until I switched to VS 2010. When that happened, I started seeing some weird behavior with my database connection string. The string (edited, but format is the same) is as follows:

<add name="DBname" connectionString="Data Source=SomeText\SomeMoreText;Initial Catalog=DB;Integrated Security=True" providerName="System.Data.SqlClient"/>

The problem is with the SomeText\SomeMoreText part.
When I run this in the debugger, the '\' is changed into '\\'. This breaks everything.

My question, which probably has an extremely simple answer is this: How can I get VS2010 to treat the connection string like a normal string without trying to insert the extra slash?

回答1:

The extra slash is not there as far as interpretation of the string is concerned. It is merely an escape character '\' before the slash '\'.

Want proof? Add the following to your code (with proper naming of course):

Debug.WriteLine(connectionStringValueHere);

Here is a small app:

        string test = "This\\is\\a\\test";

        Console.WriteLine(test);
        Debug.WriteLine(test);

        Console.Read();

Note that the string, in both console and debug (output window) is This\is\a\test. If you do the following in the immediate window when the code is at a breakpoint:

 ? test

You see the following output

? test
"This\\is\\a\\test"

But you have the escapes present, which is normal for strings in .NET.