Config database string:
<connectionStrings>
<add name= "mywebdatastring" connectionstring= "server=192.168.0.4;database=clwmsdb;uid=sa;pwd=******"/>
</connectionStrings>
Read string (2 methods):
(1) Add system.web reference
string connctionstring = system.web.configuration.webconfigurationmanager.connectionstrings["connectionString "]. ToString ();
(2) Add system.configuration reference
string connctionstring = system.configuration.configurationmanager.connectionstrings["connectionString"]. ToString ();
To read a single item:
SqlConnection con =new SqlConnection (connctionstring);
con. Open ();
string Aserver=con. datasource;//Read Server 192.168.0.4
string asql = con. database;//Read Database Clwmsdb
Description:
(1) The above method does not know why only the
server address and
database can be read, not to read the
user name and
password .
(2) The method of reading the user name and password is as follows (a stupid method, that is, to split the string ):
string[] Constr = Connctionstring.split (';');
string[] struser = constr[2]. Split (' = ');
string UserId = Struser[1]. Trim (); User name
//Password strpassword[1]. Trim ()
string[] strpassword = constr[3]. Split (' = ');
txtpassword.textmode = Textboxmode.password;
this.txtPassword.Attributes.Add ("value", strpassword[1]. Trim ());
Note: If the form is in a password box, it is best to add this.txtPassword.Attributes.Add ("value", strpassword[1]. Trim ()); Otherwise, the password is not displayed;
To
Modify a string:
Configuration config = System.Web.Configuration.WebConfigurationManager.OpenWebConfiguration ( Request.applicationpath);
connectionstringssection consection = (connectionstringssection) config. GetSection ("connectionString
s");
//modified string
string newstr = "server=" + txtServer.Text.Trim () + ";d atabase=" + txtSql.Text.Trim () + "; uid=" + Txtuser.text . Trim () + ";p wd=" + TxtPassword.Text.Trim ();
consection.connectionstrings["Mywebdatastring"]. ConnectionString = Newstr;
CONFIG. Save ();
SqlConnection conn= New SqlConnection (NEWSTR);
//Verify connectivity to the database
if (con. state = ConnectionState.Open) {
try {
con. Open ();
} catch {
Scriptmanager.registerstartupscript (this, GetType (), "AA", "alert (' Save succeeded!") But the configuration is not valid! ') ", true);
return;
}
}
Config database string read, modify