because in the WinForm design, the database connection string in the wizard is kept in app.config because it is often used to set the data source for DataGridView using the wizard. Therefore, if it involves modifying the database connection settings, you must read and write to the connectionstrings in the app.config.
1. Class Modifyappconfig for reading and writing to App.configjin
Class Modifyappconfig
{
///
Get connectionstrings
///
///
///
public string Getconnectionstringsconfig (string connectionname)
{
String connectionString = Configurationmanager.connectionstrings[connectionname]. ConnectionString;
return connectionString;
}
///
Update connection string
///
///
///
///
public void Updateconnectionstringsconfig (string newName, String newconstring, String newprovidername)
{
BOOL ismodified = false; Log whether the connection string already exists
if (Configurationmanager.connectionstrings[newname]!= null)
{
IsModified = true;
}
Create a new connection string instance
Connectionstringsettings mysettings = new Connectionstringsettings (NewName, newconstring, newprovidername);
Open the executable configuration file *.exe.config
Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);
If the connection string already exists, delete it first
if (ismodified)
{
Config. ConnectionStrings.ConnectionStrings.Remove (NewName);
Adds a new connection string to the configuration file.
Config. CONNECTIONSTRINGS.CONNECTIONSTRINGS.ADD (mysettings);
To save changes to a configuration file
Config. Save (configurationsavemode.modified);
Force the connectionstrings configuration section of the configuration file to be loaded again
Configurationmanager.refreshsection ("connectionstrings");
}
}
}
2. In the program to update the app.config, the code is as follows:
Read the connectionstrings in App.config
Modifyappconfig mac = new Modifyappconfig ();
String Strconnstrings=mac. Getconnectionstringsconfig ();
Rewriting the connectionstrings in app.config
Modifyappconfig mac = new Modifyappconfig ();
Mac. Updateconnectionstringsconfig ("BRCC.") Properties.Settings.brccConnectionString ", strconn," System.Data.SqlClient ");
This completes the reading and writing of connectionstrings in the app.config. Detailed read and write to the app.config, can refer to the following: http://yueqing.blog.163.com/blog/static/32082592009813111946229/
http://cache.baidu.com/c?m= 9d78d513d99256af59fa940f5e549571182497634bc0d1652e89cf1cc8314c41367192bc30551613a5c16b1600b8492dbbad6a2e605266ecc694c90c9 De0ce7d6e9c60742e13dc0754910eaeb85b389777d40db7f25bb0fae732e4a9d182990944ca245427dfedd81a4609ca6df21f33e9bb9a4e115e12bbfa 3012a51f28&p=983fc54ad7c905f20be291225b5f&user=baidu