Error while connecting with SQL Server named instance from C# .Net


  • Hi All,

    I am facing a strange issue. I have a sql server named instance (for example (server_name)\(instance_name)). I am able to connect to create a SQLConnection using below connection string "Data Source=ServerName;Initial Catalog=DatabaseName;Trusted_Connection=True" if I am connecting to a server without instance name. But trhis connection string fails if I try to connect to named instance. I am receiving below error.

    "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."

    Though I am able to connect to that instance using SSMS from my system.

    Even I tried to use SQLConnectionStringBuilder for for the connection string. But I am still receiving this error.

    Please help me to solve this issue.

    Friday, March 31, 2017 6:51 AM

All replies

  • Hello,

    See the following article, skip down to "Why you Can't Connect to SQL-Server" in regards to named instance.

    Please remember to mark the replies as answers if they help and unmark them if they provide no help, this will help others who are looking for solutions to the same or similar problem. Contact via my Twitter (Karen Payne) or Facebook (Karen Payne) via my MSDN profile but will not answer coding question on either.
    VB Forums - moderator
    profile for Karen Payne on Stack Exchange, a network of free, community-driven Q&A sites

    Friday, March 31, 2017 8:21 AM
  • This may sound trival, but is your connection string in the .config file, or is it written as a string in your source code? If it is a string, make sure that you escape the backslash that separates the server name from the instance name.

    For example, if you do this:

    string connectionstring = "Data Source=ServerName\nameOfInstance;...";

    then this will be interpreted as a datasource whose name contains a newline in the middle (the backslash followed by the n), instead of an instance name.

    The solution, once you know the problem, is obvious: either write

    string connectionstring = "Data Source=ServerName\\nameOfInstance;...";


    string connectionstring = @"Data Source=ServerName\nameOfInstance;...";

    It may appear something obvious and very silly, but I have actually observed this problem in applications under development more than once!

    Saturday, April 1, 2017 12:19 PM