1 // Get the application configuration file.
2 System.Configuration.Configuration config =
3 ConfigurationManager.OpenExeConfiguration(
4 ConfigurationUserLevel.None);
5 string sectionName = "appSettings";
6
7 NameValueCollection appSettings =
8 ConfigurationManager.AppSettings;
9 List<string> allDatFilesNames;
10
11 allDatFilesNames = GetAllDataFileName();
12 if (allDatFilesNames == null)
13 {
14 Environment.Exit(0);
15 }
16
17 //先清空之前的數據文件記錄
18 config.AppSettings.Settings.Clear();
19 // Save the configuration file.
20 config.Save(ConfigurationSaveMode.Modified);
21
22 // Force a reload of the changed section. This
23 // makes the new values available for reading.
24 ConfigurationManager.RefreshSection(sectionName);
25 appSettings =
26 ConfigurationManager.AppSettings;
27
28 foreach (string fullName in allDatFilesNames)
29 {
30 string fileName = Path.GetFileName(fullName);
31 if (appSettings[fileName] == null)
32 {
33 // 鍵值僅保存文件名 www.2cto.com
34 config.AppSettings.Settings.Add(fileName, GetFileItemNum(fullName).ToString());
35 }
36 else
37 {
38 // 已存在此鍵值,則僅刷新
39 config.AppSettings.Settings[fileName].Value = GetFileItemNum(fullName).ToString();
40 }
41
42
43 }
44
45 // Save the configuration file.
46 config.Save(ConfigurationSaveMode.Modified);
47
48 // Force a reload of the changed section. This
49 // makes the new values available for reading.
50 ConfigurationManager.RefreshSection(sectionName);
使用appSettings要特別注意,上面代碼中config.AppSettings.Settings和appSettings都能夠索引到鍵值,正常讀取配置文件之後,兩者是一樣的,但是,當執行了上面的config.AppSettings.Settings.Clear();之後,兩者就不同步了,config.AppSettings.Settings(配置文件裡)清空了,但是appSettings(內存裡)還有之前的記錄,(appSettings[fileName] == null)就不一定為true了,這樣直接用config.AppSettings.Settings[fileName].Value添加值,會報null異常。
所以還加了上面19~26行部分代碼,而且
appSettings =
ConfigurationManager.AppSettings;
這個給appSettings重新賦值也是必須的。
摘自 果殼中的宇宙