using System;
|
using System.Configuration;
|
using System.Diagnostics;
|
using System.IO;
|
using System.Xml.Serialization;
|
|
namespace Bro.Common.Util
|
{
|
|
/// <summary>
|
/// 配置文件帮助类
|
/// </summary>
|
public class ConfigHelper
|
{
|
|
private static object ioLock = new object();
|
|
/// <summary>
|
/// 载入XML配置文件
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="filePath"></param>
|
/// <returns></returns>
|
public static T Load<T>(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);
|
}
|
|
/// <summary>
|
/// 保存XML配置文件
|
/// </summary>
|
/// <typeparam name="T"></typeparam>
|
/// <param name="filePath"></param>
|
/// <param name="config"></param>
|
/// <returns></returns>
|
public static bool Save<T>(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;
|
}
|
|
/// <summary>
|
/// 修改AppSettings中配置
|
/// </summary>
|
/// <param name="key">key值</param>
|
/// <param name="value">相应值</param>
|
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;
|
}
|
}
|
}
|
}
|