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 // 键值仅保存文件名 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重新赋值也是必须的。