.NET Zone is brought to you in partnership with:

Robert is a South African technology specialist with focus on Microsoft technologies. He is very passionate about teaching and sharing and is a Microsoft MVP & Ranger. Robert is a DZone MVB and is not an employee of DZone and has posted 75 posts at DZone. You can read more from them at their website. View Full User Profile

Cannot Connect to LocalDB from .NET

03.16.2013
| 4535 views |
  • submit to reddit

You are trying something simple – just open a connection to a LocalDB instance from .NET but it is failing with a SqlException which has the following message:

A network-related or instance-specific error occurred while establishing a connection to SQL Server. The server was not found or was not accessible. Verify that the instance name is correct and that SQL Server is configured to allow remote connections. (provider: Named Pipes Provider, error: 40 - Could not open a connection to SQL Server)

You know LocalDB is working, since you copied the connection string from within Visual Studio, but it just doesn’t work!

The cause of this issue is the connection string, however it may not be obvious at first glance:

var sqlConnection = new SqlConnection("Data Source=(localdb)\v11.0;Initial Catalog=Astronauts;Integrated Security=True;Connect Timeout=5");

The root cause is the Data Source and the \v in it – normally when you have a \ it complains unless it is a valid escape sequence like \r or \t and since it is not complaining here, it must be a valid escape sequence, just maybe one you are not familiar with, as \v is for a vertical tab.

image

The solution is easy when you realise that the escape sequence is messing with you, just add another slash:

var sqlConnection = new SqlConnection("Data Source=(localdb)\\v11.0;Initial Catalog=Astronauts;Integrated Security=True;Connect Timeout=5");

Published at DZone with permission of Robert Maclean, author and DZone MVB. (source)

(Note: Opinions expressed in this article and its replies are the opinions of their respective authors and not those of DZone, Inc.)