應用程序配置文件,對於asp.net是 web.config,對於WINFORM程序是 App.Config(ExeName.exe.config)。web
配置文件,對於程序自己來講,就是基礎和依據,其本質是一個xml文件。app
對於配置文件的操做,從.NET 2.0 開始,就很是方便了,提供了 System [.Web] .Configuration 這個管理功能的NameSpace,要使用它,須要添加對 System.configuration.dll的引用。asp.net
咱們以最多見的 AppSettings 小節來做爲例子:this
假設有以下的配置文件內容:spa
<?xml version="1.0" encoding="utf-8" ?>.net
<configuration>code
<appSettings>xml
<add key="y" value="this is Y"/>blog
</appSettings>utf-8
</configuration>
1.命名空間
對於ASP.NET 程序, 使用 System.Web.Configuration.WebConfigurationManager;
2.讀取
System.Web.Configuration.WebConfigurationManager.AppSettings[「y」];
3.添加
須要有寫權限:
Configuration config = WebConfigurationManager.OpenWebConfiguration(null); AppSettingsSection app = config.AppSettings; app.Settings.Add("x", "this is X"); config.Save(ConfigurationSaveMode.Modified);
4.修改
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);
5.刪除
Configuration config = WebConfigurationManager.OpenWebConfiguration(null); AppSettingsSection app = config.AppSettings; app.Settings.Remove("x"); config.Save(ConfigurationSaveMode.Modified);
.
1.命名空間
對於WINFORM程序,使用 System.Configuration.ConfigurationManager;
2.讀取
System.Configuration.ConfigurationManager.AppSettings[「y」];
3.添加
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection app = config.AppSettings; app.Settings.Add("x", "this is X"); config.Save(ConfigurationSaveMode.Modified);
4.修改
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");// 刷新命名節,在下次檢索它時將從磁盤從新讀取它。記住應用程序要刷新節點
PS: 修改後,App.config文件的x節點沒有更改,而是exe.config的配置更改,讀取正常
5.刪除
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); AppSettingsSection app = config.AppSettings; app.Settings.Remove("x"); config.Save(ConfigurationSaveMode.Modified);