代码为C#操作xml配置文件的范例类,函数SetValue用于向配置文件写入一个值,GetValue用于根据Key获取相应值。这种方法的配置文件不需要手动创建,程序在运行后会自动处理创建。
注意:1.需要在解决方案上右键引用system.Configuration,并且要在单元头处using system.Configuration
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 | public class ConfigAppSettings { //写入值 public static void SetValue(String key, string value) { // Configuration LocalConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (LocalConf.AppSettings.Settings[key] == null ) { LocalConf.AppSettings.Settings.Add(key, value); } else { LocalConf.AppSettings.Settings[key].Value = value; } LocalConf.Save(ConfigurationSaveMode.Full); ConfigurationManager.RefreshSection( "appSettings" ); } //读取指定Key的值 public static string GetValue( string key) { Configuration LocalConf = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (LocalConf.AppSettings.Settings[key] == null ) return "" ; else return LocalConf.AppSettings.Settings[key].Value; } } |