123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106 |
- using System;
- using System.Collections.Generic;
- using System.IO;
- using System.Linq;
- using System.Text;
- using System.Xml.Linq;
- using System.Xml.Serialization;
- namespace SiwiFms.Helper
- {
- public class UserConfigXML
- {
- public static readonly UserConfigXML Instance = new UserConfigXML();
- private string filePath;
- private List<UserProfie> userProfies = new List<UserProfie>();
- private UserConfigXML()
- {
- filePath = Path.Combine(System.AppDomain.CurrentDomain.BaseDirectory, "UserConfig.xml");
- LoadUserConfigXML();
- }
- /// <summary>
- /// 获取指定key的值
- /// </summary>
- /// <param name="key"></param>
- /// <returns></returns>
- public string ReadSetting(string key)
- {
- var up = userProfies.FirstOrDefault(m => m.Key == key);
- if (up != null)
- return up.Value;
- else
- return string.Empty;
- }
- /// <summary>
- /// 添加一个配置
- /// </summary>
- /// <param name="key"></param>
- /// <param name="value"></param>
- public void WriteSetting(string key, string value)
- {
- var us = userProfies.FirstOrDefault(m => m.Key == key);
- if (us != null)
- userProfies.Remove(us);
- userProfies.Add(new UserProfie { Key = key, Value = value });
- SaveUserConfigXML();
- }
- /// <summary>
- /// 删除一个配置
- /// </summary>
- /// <param name="key"></param>
- public void RemoveSetting(string key)
- {
- var us = userProfies.FirstOrDefault(m => m.Key == key);
- if (us != null)
- {
- userProfies.Remove(us);
- SaveUserConfigXML();
- }
- }
- /// <summary>
- /// 保存配置
- /// </summary>
- private void SaveUserConfigXML()
- {
- try
- {
- var domLinq = new XElement("AppSettings",from c in userProfies
- select new XElement("add",new XAttribute("key",c.Key),new XAttribute("value",c.Value)));
- domLinq.Save(filePath);
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- /// <summary>
- /// 获取配置文件地址
- /// </summary>
- private void LoadUserConfigXML()
- {
- if (File.Exists(filePath))
- {
- try
- {
- XmlSerializer xs = new XmlSerializer(typeof(List<UserProfie>));
- using (FileStream fs = new FileStream(filePath, FileMode.Open, FileAccess.Read))
- {
- userProfies = (List<UserProfie>)xs.Deserialize(fs);
- }
- }
- catch(Exception ex)
- {
- Console.WriteLine(ex.Message);
- }
- }
- }
- }
- public class UserProfie
- {
- public string Key { get; set; }
- public string Value { get; set; }
- }
- }
|