Get the Server Name from Connection string Defined in App.config File?

ozzy_mra picture ozzy_mra · Mar 10, 2013 · Viewed 31.7k times · Source

I want to get IP Adress of ConnectionString's serverName from my app.config file and then ping it. Actually i want ping my server before running my application. how do i do this? my ConnectionString

<"name="ConnectionString"
 connectionString="Data Source=192.168.1.5;
                   Initial Catalog=CheckPass2;
                   User ID=User;
                   Password=myPassword" />

Answer

Bhushan Firake picture Bhushan Firake · Mar 10, 2013

How do I do this?

You can get the server address using SqlConnectionStringBuilder.The DataSource property of this class can be used for this as below:

// Retrieve the ConnectionString from App.config 
string connectString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();
SqlConnectionStringBuilder builder = new SqlConnectionStringBuilder(connectString);
// Retrieve the DataSource property.    
string IPAddress = builder.DataSource;

This DataSource property corresponds to the following keys within the connection string.

  • Data Source
  • server
  • address
  • addr and
  • network address

Regardless of which of these values has been supplied within the supplied connection string, the connection string created by the SqlConnectionStringBuilder will use the well-known "Data Source" key.