RetroCoder
RetroCoder

Reputation: 2685

How do I retrieve both the server name and database name from a connection string in web.config

How do I retrieve both the Server Name and Database Name from a web.config connection string programatically through the .net api? Preferably without using an html or xml parser I create. Looking for the simplest way to retrieve this type of information. Example web.config snippet:

<?xml version="1.0" encoding="utf-8"?>
<configuration>
  <connectionStrings>
    <add name="ConnectionString" connectionString="Provider=SQLOLEDB;Data Source=MyServer;User ID=admind;password=ju7mpst@rterz_Fak3;Initial Catalog=dbDatabase" providerName="System.Data.OLEPlethora"/>
  </connectionStrings>
<system.web>

result: server=MyServer database=dbDatabase

Found this link regarding retreiving connection string settings. This appears to be much simplier, however, I'm not sure if I can iterate over many connection string.

Upvotes: 0

Views: 2476

Answers (1)

oɔɯǝɹ
oɔɯǝɹ

Reputation: 7625

Get the connectionstring from config as such:

var myConnectionString = ConfigurationManager.ConnectionStrings["ConnectionString"].ToString();

You can then use the oledb connectionstring builder to parse any connectionstring and extract the relevant parts.

var builder = new System.Data.OleDb.OleDbConnectionStringBuilder(myConnectionString);
var servername = builder["Data Source"];
var database = builder["Initial Catalog"];

Console.WriteLine("server={0}, database={1}", servername, database);

Upvotes: 4

Related Questions