using System; using System.Configuration; using System.Diagnostics; using System.IO; using System.Xml.Serialization; namespace Bro.Common.Util { /// /// 配置文件帮助类 /// public class ConfigHelper { private static object ioLock = new object(); /// /// 载入XML配置文件 /// /// /// /// public static T Load(string filePath) { try { lock (ioLock) { if (!File.Exists(filePath)) { return default(T); } var fs = new FileStream(filePath, FileMode.Open); var xs = new XmlSerializer(typeof(T)); var config = (T)xs.Deserialize(fs); fs.Close(); return config; } } catch(Exception ex) { Trace.TraceError("ConfigHelper load fail, filepath:{0},ex:{1}", filePath, ex); } return default(T); } /// /// 保存XML配置文件 /// /// /// /// /// public static bool Save(string filePath, T config) { try { lock(ioLock) { var fs = new FileStream(filePath, FileMode.Create, FileAccess.Write, FileShare.None); var xs = new XmlSerializer(typeof(T)); xs.Serialize(fs, config); fs.Close(); } return true; } catch(Exception ex) { Trace.TraceError("ConfigHelper Save fail, filepath:{0},ex:{1}", filePath, ex); } return false; } /// /// 修改AppSettings中配置 /// /// key值 /// 相应值 public static bool SetConfigValue(string key, string value) { try { Configuration config = ConfigurationManager.OpenExeConfiguration(ConfigurationUserLevel.None); if (config.AppSettings.Settings[key] != null) config.AppSettings.Settings[key].Value = value; else config.AppSettings.Settings.Add(key, value); config.Save(ConfigurationSaveMode.Modified); ConfigurationManager.RefreshSection("appSettings"); return true; } catch { return false; } } } }