Get user and password from ConnectionStringSettings

msfanboy picture msfanboy · Oct 26, 2011 · Viewed 17.7k times · Source

How can I get the user and password from such a connectionString in the app.config with a .NET function?

Of course I could read that string and get the value after the ID= and Password=.

<connectionStrings>
<add name="MyConString" connectionString="Data Source=(local);Initial Catalog=MyDatabase;Persist Security Info=True;User ID=MyUsername Password=MyPassword;Connect  providerName="System.Data.SqlClient"/>    
</connectionStrings>

Answer

Tomas Walek picture Tomas Walek · Oct 26, 2011

use the ConnectionBuilderClass

SqlConnectionStringBuilder builder =  new SqlConnectionStringBuilder("Your connection string");
string password = builder.Password;


together with the

string connString = ConfigurationManager.ConnectionStrings["MyConString"].ConnectionString;

to achieve this.