配置文件项目学习分享

           建设一个对配置文件方便快捷操作的项目,是一个项目重要的建设模块之一,项目中很多方法都需要调用配置文件中的配置信息进行后续操作。以下是DNT发布包中的配置文件信息。

  

    其实道理也很简单,就是将实体对象的状态序列化并且写入到配置文件中。需要用到的时候读取出配置文件反序列化成对象即可。但是也要考虑到一些因素,比如配置文件是否存在,配置文件最初的配置呈现,配置文件的保存路径,等等,这就需要我们自己对代码进行加工了。

    config文件为XML格式文档,当然对其操作也少不了对其相关类的引用了。

    using System.Xml;
    using System.Xml.Serialization;

     本项目内容不多,言简意赅,分为两部分,一是加载数据,二是保存(更新)数据。  

    加载数据:这里的加载数据,即将配置文件中的数据反序列化成对象,返回对象,方便开发人员对配置文件对象进行配置。为了方便公用,将其写作泛型方法。

 1         /// <summary>
 2         /// 获取配置信息
 3         /// </summary>
 4         /// <typeparam name="T">配置信息类</typeparam>
 5         /// <returns></returns>
 6         public static T GetConfig<T>() where T : class, new()
 7         {
 8             string configFilePath = GetConfigFilePath<T>();       
 9             return (T)DeserializeInfo<T>(configFilePath, typeof(T));
10         }

                GetConfigFilePath方法 为获得配置文件路径,通常存放于根目录的Config文件夹中,也可对此方法进行修改,完成对配置文件存放目录的指定。

获得文件所在路径
 1         /// <summary>
 2         /// 获得文件所在路径
 3         /// </summary>
 4         /// <typeparam name="T">配置信息类</typeparam>
 5         /// <returns></returns>
 6         public static string GetConfigFilePath<T>()
 7         {
 8             string path = System.Web.HttpContext.Current.Server.MapPath("~/Config/");
 9             return path + typeof(T).Name + (".config");
10         }

                DeserializeInfo方法 是指定目录的配置文件进行反序列化成对象。

将配置文件反序列化成对象
 1         #region 反序列化指定的类 + static IConfigInfo DeserializeInfo(string configFilePath, Type configType)
 2         /// <summary>
 3         /// 反序列化指定的类
 4         /// </summary>
 5         /// <param name="configFilePath">config文件的路径</param>
 6         /// <param name="configType">指定的类型</param>
 7         /// <returns></returns>
 8         public static T DeserializeInfo<T>(string configFilePath, Type configType) where T : class,new()
 9         {
10             string configChacheKey = "CK_SiteConfigCode_" + configType.Name;        
11             T configinfo = SiteCache.Get<T>(configChacheKey);         
12 
13             if (configinfo == null)
14             {
15                 if (IsGenner(configFilePath, (T)Activator.CreateInstance(configType)) == false)      //判断是否有文件,没有则生成
16                 {
17                     using (XmlTextReader xmlTextReader = new XmlTextReader(configFilePath))
18                     {
19                         XmlSerializer xmlSerializer = new XmlSerializer(configType);
20                         configinfo = (T)xmlSerializer.Deserialize(xmlTextReader);
21                     }
22                 }
23                 else
24                 {
25                     configinfo = new T();
26                 }
27                 SiteCache.Get<T>(configChacheKey, () => configinfo, new CacheDependency(configFilePath));
28             }
29             return configinfo;
30         }
31         #endregion

              在DeserializeInfo方法中,有一段是用来判断是否存在配置文件的方法,如果存在,则直接反序列化成对象,然后返回给GetConfig方法中。如果不存在配置文件,则自动生成配置文件,即 IsGenner方法 。考虑到不断反序列化影响性能,将对象加入到缓存。

      

 1        #region 是否存在配置文件(没有则生成) + static bool IsGenner<T>(string configFilePath, T configInfo)
 2         /// <summary>
 3         /// 判断是否存在配置文件(没有则生成)
 4         /// </summary>
 5         /// <param name="configFilePath">配置文件路径</param>
 6         /// <param name="configInfo">临时配置变量</param>
 7         /// <returns></returns>
 8         public static bool IsGenner<T>(string configFilePath, T configInfo)
 9         {
10             string directoryPath = System.Web.HttpContext.Current.Server.MapPath("/Config");
11 
12             if (!Directory.Exists(directoryPath))
13             {
14                 Directory.CreateDirectory(directoryPath);
15             }
16 
17             FileInfo fileInfo = new FileInfo(configFilePath);
18             if (!System.IO.File.Exists(configFilePath) || fileInfo.Length == 0)
19             {
20                 if (configInfo == null)
21                 {
22                     return false;
23                 }
24                 using (FileStream fs = new FileStream(configFilePath, FileMode.OpenOrCreate, FileAccess.Write, FileShare.ReadWrite))
25                 {
26                     XmlSerializer xml = new XmlSerializer(configInfo.GetType());
27                     xml.Serialize(fs, configInfo);
28                 }
29                 return true;
30             }
31             return false;
32         }
33         #endregion

    如果不存在配置文件,生成后,直接new 一个对象返回给GetConfig()方法。同时也跳过序列化数据这段代码,在这里,第一部分加载数据就这样了。

           保存(更新)配置文件:传入一个实例对象,对实例对象进行序列化,并将内容进行写入到配置文件中,达到更新配置文件信息的效果。

          

 1    #region 保存(序列化)指定路径下的配置文件 + public static bool SaveConfig<T>(string configFilePath, T configInfo)
 2         /// <summary>
 3         ///保存(序列化)指定目录下文件的配置信息 
 4         /// </summary>
 5         /// <typeparam name="T">配置信息类</typeparam>
 6         /// <param name="configFilePath">配置信息文件路径</param>
 7         /// <param name="configInfo">配置信息</param>
 8         /// <returns></returns>
 9         public static void SaveConfig<T>(string configFilePath, T configInfo)
10         {
11             Type configType = typeof(T);
12 
13             if (IsGenner(configFilePath, configInfo) == false)
14             {
15                 try
16                 {
17                     XmlSerializer xmlSerializer = new XmlSerializer(configType);
18                     using (XmlTextWriter xmlTextWriter = new XmlTextWriter(configFilePath, Encoding.UTF8))
19                     {
20                         xmlTextWriter.Formatting = Formatting.Indented;
21                         XmlSerializerNamespaces xmlNamespace = new XmlSerializerNamespaces();
22                         xmlNamespace.Add(string.Empty, string.Empty);
23                         xmlSerializer.Serialize(xmlTextWriter, configInfo, xmlNamespace);
24                     }
25                 }
26                 catch (SecurityException ex)
27                 {
28                     throw new SecurityException(ex.Message, ex.DenySetInstance, ex.PermitOnlySetInstance, ex.Method, ex.Demanded, (IPermission)ex.FirstPermissionThatFailed);
29                 }
30             }
31         }
32         #endregion

       所有的配置信息实体类,继承于这个配置信息操作基类即可。

原文地址:https://www.cnblogs.com/yangda/p/2941822.html