Tomtom
Tomtom

Reputation: 9394

Move ConnectionString to App.config

In my WPF-Application I want to connect to a database.

If I use the following code it just works fine:

string connectionString = @"Data Source=SERVER\ENGINE;Initial Catalog=MyDb;User ID=sa;Password=123456;";
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

Now I moved the ConnectionString to my App.config and want to use from there with the following code:

string connectionString = ConfigurationManager.ConnectionStrings[0].ConnectionString;
SqlConnection connection = new SqlConnection(connectionString);
connection.Open();

Now I get an SqlExecption:

An unhandled exception of type 'System.Data.SqlClient.SqlException' occurred in System.Data.dll

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: SQL Network Interfaces, error: 26 - Error Locating Server/Instance Specified)

The App.config looks like:

<?xml version="1.0" encoding="utf-8" ?>
<configuration>
    <startup> 
        <supportedRuntime version="v4.0" sku=".NETFramework,Version=v4.5" />
    </startup>
  <connectionStrings >
    <add connectionString="Data Source=SERVER\ENGINE;Initial Catalog=MyDb;User ID=sa;Password=123456;" name="connection"/>
  </connectionStrings>
</configuration>

Why does this not work?

Upvotes: 0

Views: 1679

Answers (2)

Rahul Singh
Rahul Singh

Reputation: 21825

Try this:- (Prefer Names instead of index)

ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

You can read why we should Here.

Upvotes: 2

HUEbeiro
HUEbeiro

Reputation: 11

You can always get the connection string by its name parameter:

ConfigurationManager.ConnectionStrings["connection"].ConnectionString;

Source: http://msdn.microsoft.com/pt-br/library/ms178411(v=vs.100).aspx?cs-save-lang=1&cs-lang=csharp#code-snippet-1

Upvotes: 1

Related Questions