配置文件的操作主要有获取根目录和获取配置key的值value,下面是总结的配置文件操作类AppConfigUtil的代码。
namespace Tmac.Utilities { /// <summary> /// 配置文件操作类 /// </summary> public class AppConfigUtil { /// <summary> /// get base directory /// </summary> public static string baseDirectory = AppDomain.CurrentDomain.BaseDirectory; #region Private method /// <summary> /// get value by key /// </summary> /// <param name="key">key</param> /// <returns>path</returns> private static string GetAppSetting(string key) { if (ConfigurationManager.AppSettings.Count == 0 || !ConfigurationManager.AppSettings.HasKeys()) { return string.Empty; } if (!ConfigurationManager.AppSettings.AllKeys.Any(p => p.Equals(key))) { return string.Empty; } return ConfigurationManager.AppSettings[key]; } /// <summary> /// get complete path by key /// </summary> /// <param name="key"></param> /// <returns></returns> private static string GetCompletePath(string key) { string value = GetAppSetting(key); if (String.IsNullOrEmpty(value)) { value = baseDirectory; } else if (!Regex.IsMatch(value, @"\A[a-zA-Z]\:\\")) { value = Path.Combine(baseDirectory,value); } return value; } #endregion #region Public Property public static string TestKey { get { return GetAppSetting("TestKey"); } } public static string FilePath { get { return GetAppSetting("FilePath"); } } public static Boolean IsCustomException { get { return "true".Equals(GetAppSetting("IsCustomException"), StringComparison.OrdinalIgnoreCase); } } #endregion } }