Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get user and password from ConnectionStringSettings

Tags:

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> 
like image 710
msfanboy Avatar asked Oct 26 '11 08:10

msfanboy


People also ask

How to get username and password from connection string in c#?

string database = builder["Initial Catalog"] as string; string UserID = builder["User ID"] as string; string password = builder["Password"] as string; This way you can get all the properties.

How do you escape special characters in connection string?

Special characters can be escaped by encapsulating them in curly brackets {...}. When there is an un-escaped special character in the ODBC connection string the software will raise an error similar to: "Format of the initialization string does not conform to specification starting at index 90."


2 Answers

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.

like image 82
Tomas Walek Avatar answered Oct 21 '22 01:10

Tomas Walek


SqlConnectionStringBuilder con = new SqlConnectionStringBuilder(ConfigurationManager.ConnectionStrings["ConnString"].ConnectionString); string myUser = con.UserID; string myPass = con.Password; 
like image 26
Ira Rainey Avatar answered Oct 21 '22 01:10

Ira Rainey