摘要:[ASP.NET],[C#]app.config與web.config的增加、刪除、修改操作
應用程式組態檔,對於asp.net是web.config,對於WindowsForm程式則是App.config(執行檔名稱.exe.config)。組態檔對於程式本身來說,就是基礎和依據,其本質是一個xml檔案,對於組態檔的操作,從.net2.0開始就方常的方便了,提供了System.Web.Configuration與System.Configuration兩個命名空間,要使用它,需要加入參考。
在WindowsForm中使用System.Configuration.ConfigurationManager
在ASP.NET中使用System.Web.Configuration.WebConfigurationManager
對於組態檔內容的讀取,實在是太方便了XD。
實作:
加入組態檔
以一小段App.config的內容來實作:
組態檔的內容如下:
1.讀取值:
Asp.Net:System.Web.Configuration.WebConfigurationManager.AppSettings["A"];
WinForm:System.Configuration.ConfigurationManager.AppSettings["A"];
2.增加
ASP.NET(需要有寫入權限)
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("B", "This is B value");
config.Save(ConfigurationSaveMode.Modified);
WinForm
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
app.Settings.Add("B", "This is B value");
config.Save(ConfigurationSaveMode.Modified);
3.修改
ASP.NET(需要有寫入權限)
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
//app.Settings.Add("B", "This is B value");
app.Settings["A"].Value = "This is not B";
config.Save(ConfigurationSaveMode.Modified);
WinForm
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
//app.Settings.Add("B", "This is B value");
app.Settings["A"].Value = "This is not B";
config.Save(ConfigurationSaveMode.Modified);
4.刪除
ASP.NET(需要有寫入權限)
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = WebConfigurationManager.OpenWebConfiguration(null);
AppSettingsSection app = config.AppSettings;
//app.Settings.Add("B", "This is B value");
//app.Settings["A"].Value = "This is not B";
app.Settings.Remove("A");
config.Save(ConfigurationSaveMode.Modified);
WinForm
//Configuration與AppSettingsSection必須引用System.Configuration才可使用!
Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None);
AppSettingsSection app = config.AppSettings;
//app.Settings.Add("B", "This is B value");
//app.Settings["A"].Value = "This is not B";
app.Settings.Remove("A");
config.Save(ConfigurationSaveMode.Modified);
以上就是對組態檔的增加/修改/刪除
另外也可以將連線資料庫的連線字串寫在組態檔內方便修改
如下:
組態檔內容:
讀取:
ConfigurationManager.ConnectionStrings["connDB"].ConnectionString;
//讀取name為connDB的連線字串
完畢!
我只是個小小的入門者