/// <summary>
        /// 从某个配置文件中读取键为key的项的值
        /// </summary>
        /// <param name="file"></param>
        /// <param name="key"></param>
        /// <returns></returns>
        protected string GetConfig(string file, string key)
        {
            string ret = null;

            if (File.Exists(file))
            {
                try
                {
                    XmlSerializer ser = new XmlSerializer(typeof(List <MyKeyValuePair>));
                    using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
                    {
                        List <MyKeyValuePair> items = ser.Deserialize(fs) as List <MyKeyValuePair>;
                        if (items != null && items.Count > 0)
                        {
                            MyKeyValuePair kv = items.SingleOrDefault(it => it.Key == key);
                            ret = kv != null ? kv.Value : null;
                        }
                    }
                }
                catch (Exception ex)
                {
                    ExceptionPolicy.HandleException(ex);
                }
            }
            return(ret);
        }
Пример #2
0
 /// <summary>
 /// 将某个配置保存到某个配置文件中
 /// </summary>
 /// <param name="file"></param>
 /// <param name="key"></param>
 /// <param name="value"></param>
 protected void SaveConfig(string file, string key, string value)
 {
     try
     {
         XmlSerializer         ser   = new XmlSerializer(typeof(List <MyKeyValuePair>));
         List <MyKeyValuePair> items = null;
         if (File.Exists(file))
         {
             using (FileStream fs = new FileStream(file, FileMode.Open, FileAccess.Read))
             {
                 items = ser.Deserialize(fs) as List <MyKeyValuePair>;
             }
         }
         if (items == null)
         {
             items = new List <MyKeyValuePair>();
         }
         var            mykey = string.Format("{0}_{1}", this.GetType().Name, key);
         MyKeyValuePair kv    = items.SingleOrDefault(it => it.Key == mykey);
         if (kv != null)
         {
             kv.Value = value;
         }
         else
         {
             items.Add(new MyKeyValuePair {
                 Key = mykey, Value = value
             });
         }
         using (FileStream fs = new FileStream(file, FileMode.Create, FileAccess.Write))
         {
             ser.Serialize(fs, items);
         }
     }
     catch (Exception ex)
     {
         ExceptionPolicy.HandleException(ex);
     }
 }