Search code examples
c#connection-stringapp-config

Get user and password from ConnectionStringSettings


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>

Solution

  • 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.