When developing a web project, a configuration file web. config is used to store global variables, such as strings used to connect to the database. Correspondingly, when developing the winform program, there is also a configuration file, which is the app. config, the role of this file and web. config is roughly the same. It can also be used to store global variables and value values used by the program.
1. Create app. config
You can add an app in this way. config File: add the app in Solution Explorer. right-click the project name in the config file and choose "add"> "new item"> "application configuration file". You can use the default name directly.
2. Use app. config
Let's look at an example of the app. config file:
<Configuration>
<Deleetask>
<Add key = "connectionstring" value = "Server = 20110823-1327 \ test; database = login; Integrated Security = true;"/>
</Appsettings>
</Configuration>
As you can see, app. config is the same as Web. config. Well, it is also an XML file. So how can we read the elements in this file? The Code is as follows:
String sqlconnectionstring = system. configuration. configurationmanager. etettings ["connectionstring"]. tostring ();
3. Modify app. config
In this way, you can read the value of the imgpath element in the app. config file. So how can we rewrite the element value? In. when modifying the element value of the config file. config files are treated as common XML files, using system. XML. the xmldocument class calls this app. the config file is read to the memory and passed to the system. XML. the xmlnode class finds the deleettings node and uses the system. XML. the xmlelement class finds an element under a node and uses the setattribute method to modify the value of this element. the config file is saved to the original directory, so that the modification of an element value is complete. The following method can be used to modify any element of the appsettings node in the app. config file. Of course, you may also modify this method to modify the value of any node or element.
Public static void setvalue (string appkey, string appvalue)
{
System. xml. xmldocument xdoc = new system. xml. xmldocument ();
Xdoc. Load (system. Windows. Forms. application. executablepath + ". config ");
System. xml. xmlnode xnode;
System. xml. xmlelement xelem1;
System. xml. xmlelement xelem2;
Xnode = xdoc. selectsinglenode ("// appsettings ");
Xelem1 = (system. xml. xmlelement) xnode. selectsinglenode ("// Add [@ key = '" + appkey + "']");
If (xelem1! = NULL) xelem1.setattribute ("value", appvalue );
Else
{
Xelem2 = xdoc. createelement ("add ");
Xelem2.setattribute ("key", appkey );
Xelem2.setattribute ("value", appvalue );
Xnode. appendchild (xelem2 );
}
Xdoc. Save (system. Windows. Forms. application. executablepath + ". config ");
}