The application configuration file for ASP. NET is Web. config for the WinForm program is app. config (ExeName.exe.config).
Configuration file, for the program itself, is the basis and basis, its essence is an XML file, for the operation of the configuration file, starting from. NET 2.0, it is very convenient to provide System [. WEB]. The Configuration of this management function namespace, to use it, you need to add a reference to System.configuration.dll.
For WinForm programs, use System.Configuration.ConfigurationManager;
For an ASP. NET program, use System.Web.Configuration.WebConfigurationManager;
We use the most common AppSettings section as an example:
Assume the following configuration file contents:
<?xml version= "1.0" encoding= "Utf-8"?>
<configuration>
<appSettings>
<add key= "y" value= "This is Y"/>
</appSettings>
</configuration>
1. Read the value:
asp:
system.web.configuration.webconfigurationmanager.appsettings["Y"];
WinForm:
system.configuration.configurationmanager.appsettings["Y"];
2. Add an item
ASP. NET (requires Write permission):
Configuration config = webconfigurationmanager.openwebconfiguration (null);
Appsettingssection app = config. AppSettings;
App. Settings.add ("x", "This is X");
Config. Save (configurationsavemode.modified);
WinForm:
Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);
Appsettingssection app = config. AppSettings;
App. Settings.add ("x", "This is X");
Config. Save (configurationsavemode.modified);
3. Modify one of the
asp
Configuration config = webconfigurationmanager.openwebconfiguration (null);
Appsettingssection app = config. AppSettings; App. Settings.add ("x", "This is X");
App. settings["X"]. Value = "This is not Y";
Config. Save (configurationsavemode.modified);
WinForm
Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);
Appsettingssection app = config. AppSettings; App. Settings.add ("x", "This is X");
App. settings["X"]. Value = "This is not Y";
Config. Save (configurationsavemode.modified);
Configurationmanager.refreshsection ("appSettings");//refreshes the named section and re-reads it from disk the next time it is retrieved. Remember that the application will refresh the node
"After the modification, the X node of the app. Config file has not changed, but the configuration change of the exe.config, read normal"
4. Delete an item
asp
Configuration config = webconfigurationmanager.openwebconfiguration (null);
Appsettingssection app = config. AppSettings;
App. Settings.remove ("X");
Config. Save (configurationsavemode.modified);
WinForm
Configuration config = configurationmanager.openexeconfiguration (configurationuserlevel.none);
Appsettingssection app = config. AppSettings;
App. Settings.remove ("X");
Config. Save (configurationsavemode.modified);
C # WinForm in the app. Config file configuration