TargetofGravity TargetofGravity - 1 year ago 255
C# Question

C# sqlConnection authentication exception

Working on writing a C# application which will query a SQL Server 2008 R2 database instance. My code (with mods to the connection string) is as follows:

using System;
using System.Collections.Generic;
using System.Data.SqlClient;
using System.Data;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace MosaiqToCTWorklist
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : Window
// Establish a connection string
string connectionString = "Data Source=IPADDRESS;Password=PASSWORD;User ID=USERID;Initial Catalog=dbName";
SqlConnection dbConnection;

public MainWindow()
dbConnection = new SqlConnection(connectionString);

private void Test()

This is my first time connecting to a database and utilized the Project > Add new data source wizard to generate the connection string defined in
. The
method was just for debugging purposes.

I'm getting the following InnerException:

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)"}

I'm at a level I do not understand why I can connect to this database using the source wizard but it fails when I write out the code. I was not able to find anything this specific and am hopeful for some additional insight as to what Visual Studio 2012 is doing behind the scenes. Thank you.

Specific Error Message

Answer Source

The error you are having is not related to your code, it is caused from the parameters you have in the connection string. It cannot find the Server.

To connect to SQL Server sometimes is not enough to specify the IP address or server name only, you need to specify the port if it is not the default one (usually 1433) and the instance name. For example, using SQL Server Express by default it creates the instance named "SQLEXPRESS", so to be able to connect to it you need to include it in the server name/IP address:

string connectionString = "Data Source=IpAddress\InstanceName,Port; Password=PWD; User ID=USERID; Initial Catalog=dbName";

Take a look here: SQL Server 2008 ConnectionStrings it is all explained there. Hope this helps!

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download