摘自:http://edu.admin5.com/article/20110124/0124431N2011.shtml
C# 應用程式設定 來源: 字型:[大 中 小]
C# 應用程式設定
官方參考:http://msdn.microsoft.com/zh-cn/library/k4s6c3a0(v=VS.80).aspx
使用VS內建的應用程式設定功能
- 建立項目
- 選擇菜單 [項目] > [屬性]
- 選擇 [設定]
就可手動添加應用程式設定了。
添加成功後,系統會自動產生App.config檔案。
view sourceprint?
01 |
<?xml version="1.0" encoding="utf-8"?> |
04 |
<WindowsApplication5.Properties.Settings> |
05 |
<setting name="mySet" serializeAs="String"> |
06 |
<value>testSet_828</value> |
08 |
<setting name="FormTitle" serializeAs="String"> |
09 |
<value>FormTestdddd</value> |
11 |
</WindowsApplication5.Properties.Settings> |
關於User和Application的區別
- Application 不允許在程式中更新設定。只能手動更改App.config或到項目屬性的設定中更改。
- User 允許在程式中更改設定。
VS也提供了一種直接在表單控制項屬性的ApplicationSettings 裡設定分支機構應用程式的快捷方法。
以下列舉了使用VS內建應用程式應注意的地方
- 如果範圍是Application時,在程式此值時唯讀。只能通過修改App.config的對應項來更改。
- 如果範圍是User,並且在程式未對此值做修改時,修改App.config對應項,在程式訪問時當前值為App.config中設定的值。
- 如果範圍是User,並且在程式中對此值進行了修改,App.config中記錄的還會是老值,並且以後的App.config此項設定將無效。
那到底User修改後的值系統在什麼地方存這呢?
經過測試是在C:\Documents and Settings\Administrator\Local Settings\Application Data\Phook\WindowsApplication5.exe_Url_nlwmvagksxwiigfpn5ymssyrjtyn22ph\1.0.0.0\user.config
下存著,如果更改以上App.config則程式將取到新值。很奇怪,微軟為什麼要弄的怎麼複雜。
在程式中使用
view sourceprint?
2 |
label1.Text = Properties.Settings.Default.mySet; |
3 |
label2.Text = Properties.Settings.Default.myApp; |
5 |
Properties.Settings.Default.mySet = "test1111"; |
6 |
Properties.Settings.Default.Save(); |
總結
- 應該是如果選擇範圍是User時,此設定是使用者層級的。使用不同使用者登入後運行程式取的值是不一樣的。
- 並且如果程式修改了名稱,各自會擁有另一套App.config。
- 而Application是應用程式級的,任何開啟相同程式的Application都會一樣。
自訂App.config
可能你想要一個Config可以功能和Application範圍一樣,但有同時支援程式修改。以下是實現方法
建立工程
手動添加App.config
格式如下:
view sourceprint?
1 |
<?xml version="1.0" encoding="utf-8" ?> |
4 |
<add key="y" value="this is Y"/> |
引用 System.Configuration
把對App.config的操作合并成了一個類方便調用。
view sourceprint?
02 |
using System.Collections.Generic; |
04 |
using System.Configuration; |
06 |
//注意需要引用 System.Configuration |
08 |
public class AppConfig |
10 |
private static Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); |
15 |
/// <param name="key"></param> |
16 |
/// <returns></returns> |
17 |
public static string GetValue(string key) |
19 |
string strReturn = null; |
20 |
if (config.AppSettings.Settings[key] != null) |
22 |
strReturn = config.AppSettings.Settings[key].Value; |
30 |
/// <param name="key"></param> |
31 |
/// <param name="value"></param> |
32 |
public static void SetValue(string key, string value) |
34 |
if (config.AppSettings.Settings[key] != null) |
36 |
config.AppSettings.Settings[key].Value = value; |
40 |
config.AppSettings.Settings.Add(key, value); |
42 |
config.Save(ConfigurationSaveMode.Modified); |
48 |
/// <param name="key"></param> |
49 |
public static void DelValue(string key) |
51 |
config.AppSettings.Settings.Remove(key); |
使用方法
view sourceprint?
2 |
AppConfig.SetValue("dtNow", DateTime.Now.Millisecond.ToString()); |
4 |
label1.Text = AppConfig.GetValue("dtNow"); |