ModelXmlReadWrite.cs 10 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305
  1. using System;
  2. using System.Collections.Generic;
  3. using System.IO;
  4. using System.Linq;
  5. using System.Security.Cryptography;
  6. using System.Text;
  7. using System.Threading.Tasks;
  8. using System.Xml;
  9. using System.Xml.Linq;
  10. using System.Xml.Serialization;
  11. namespace XmlClass
  12. {
  13. public class ModelXmlReadWrite
  14. {
  15. private static readonly ModelXmlReadWrite modelXmlReadWrite = new ModelXmlReadWrite();
  16. private string XmlEncryptionString = "jiuzhankejijiami";
  17. string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Config.xml";
  18. private ModelXmlReadWrite() { }
  19. public static ModelXmlReadWrite GetModelXmlReadWrite()
  20. {
  21. return modelXmlReadWrite;
  22. }
  23. /// <summary>
  24. /// 封装一个继承StringWrite的方法(可定义Encoding)
  25. /// </summary>
  26. public sealed class StringWriterWithEncoding : StringWriter
  27. {
  28. private readonly Encoding encoding;
  29. public StringWriterWithEncoding(Encoding encoding)
  30. {
  31. this.encoding = encoding;
  32. }
  33. public override Encoding Encoding
  34. {
  35. get
  36. {
  37. return encoding;
  38. }
  39. }
  40. }
  41. /// <summary>
  42. /// 写入Xml
  43. /// 使用方法 WriteXml(Model)
  44. /// </summary>
  45. /// <param name="obj"></param>
  46. /// <returns></returns>
  47. public string WriteXml(object obj)
  48. {
  49. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  50. string content = string.Empty;
  51. //序列化
  52. using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
  53. {
  54. serializer.Serialize(writer, obj);
  55. content = writer.ToString();
  56. }
  57. //保存文件
  58. using (StreamWriter stream_writer = new StreamWriter(path, false, Encoding.UTF8))
  59. {
  60. stream_writer.Write(content);
  61. }
  62. return content;
  63. }
  64. /// <summary>
  65. /// 写入Xml,带路径
  66. /// 使用方法 WriteXml(Model)
  67. /// </summary>
  68. /// <param name="obj"></param>
  69. /// <returns></returns>
  70. public string WriteXml(object obj,string WXPath)
  71. {
  72. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  73. string content = string.Empty;
  74. //序列化
  75. using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
  76. {
  77. serializer.Serialize(writer, obj);
  78. content = writer.ToString();
  79. }
  80. //保存文件
  81. using (StreamWriter stream_writer = new StreamWriter(WXPath, false, Encoding.UTF8))
  82. {
  83. stream_writer.Write(content);
  84. }
  85. return content;
  86. }
  87. /// <summary>
  88. /// 写入Xml(带加密)
  89. /// </summary>
  90. /// <param name="obj">Model值</param>
  91. /// <param name="IsEncryption">是否加密</param>
  92. /// <returns></returns>
  93. public string WriteXml(object obj,bool IsEncryption)
  94. {
  95. XmlSerializer serializer = new XmlSerializer(obj.GetType());
  96. string content = string.Empty;
  97. //序列化
  98. using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
  99. {
  100. serializer.Serialize(writer, obj);
  101. content = writer.ToString();
  102. }
  103. //保存文件
  104. using (StreamWriter stream_writer = new StreamWriter(path, false, Encoding.UTF8))
  105. {
  106. stream_writer.Write(content);
  107. }
  108. if (IsEncryption)
  109. {
  110. XmlEncryption(path);
  111. }
  112. return content;
  113. }
  114. /// <summary>
  115. /// 读取Xml
  116. /// 使用方法 Model=(Model)ReadXml(typeof(Model))
  117. /// </summary>
  118. /// <param name="object_type">typeof(Model)</param>
  119. /// <returns></returns>
  120. public object ReadXml(Type object_type,string XRPath)
  121. {
  122. XmlSerializer serializer = new XmlSerializer(object_type);
  123. using (StreamReader reader = new StreamReader(XRPath, Encoding.UTF8))
  124. {
  125. //反序列化
  126. return serializer.Deserialize(reader);
  127. }
  128. }
  129. /// <summary>
  130. /// 读取Xml
  131. /// 使用方法 Model=(Model)ReadXml(typeof(Model))
  132. /// </summary>
  133. /// <param name="object_type">typeof(Model)</param>
  134. /// <returns></returns>
  135. public object ReadXml(Type object_type)
  136. {
  137. XmlSerializer serializer = new XmlSerializer(object_type);
  138. using (StreamReader reader = new StreamReader(path,Encoding.UTF8))
  139. {
  140. //反序列化
  141. return serializer.Deserialize(reader);
  142. }
  143. }
  144. /// <summary>
  145. /// 读取Xml
  146. /// 使用方法 Model=(Model)ReadXml(typeof(Model))
  147. /// </summary>
  148. /// <param name="object_type"></param>
  149. /// <param name="IsEncryption"></param>
  150. /// <returns></returns>
  151. public object ReadXml(Type object_type, bool IsEncryption)
  152. {
  153. object result = null;
  154. if (IsEncryption)
  155. {
  156. XmlDecrypt(path);
  157. }
  158. XmlSerializer serializer = new XmlSerializer(object_type);
  159. using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
  160. {
  161. result = serializer.Deserialize(reader);
  162. //反序列化
  163. }
  164. if (IsEncryption)
  165. {
  166. XmlEncryption(path);
  167. }
  168. return result;
  169. }
  170. public bool CheckConfigDafaultPath()
  171. {
  172. bool result = false;
  173. try
  174. {
  175. if(File.Exists(path))
  176. {
  177. result = true;
  178. }
  179. }
  180. catch
  181. {
  182. }
  183. return result;
  184. }
  185. /// <summary>
  186. /// Xml秘钥加密
  187. /// </summary>
  188. /// <param name="XmlPath"></param>
  189. private void XmlEncryption(string XmlPath)
  190. {
  191. string XmlText = "";
  192. XmlDocument xmlDoc = new XmlDocument();
  193. XmlDocument result = new XmlDocument();
  194. xmlDoc.PreserveWhitespace = true;
  195. xmlDoc.Load(XmlPath);//加载要加密的XML文件
  196. XmlText = xmlDoc.InnerXml;
  197. if (string.IsNullOrEmpty(XmlText)) return;
  198. try
  199. {
  200. Byte[] toEncryptArray = Encoding.UTF8.GetBytes(XmlText);
  201. RijndaelManaged rm = new RijndaelManaged
  202. {
  203. //设置密钥:key为32位=数字或字母16个=汉字8个
  204. Key = Encoding.UTF8.GetBytes(XmlEncryptionString),
  205. Mode = CipherMode.ECB,
  206. Padding = PaddingMode.PKCS7
  207. };
  208. ICryptoTransform cTransform = rm.CreateEncryptor();
  209. Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  210. string MessageValue = Convert.ToBase64String(resultArray, 0, resultArray.Length);
  211. //创建类型声明节点
  212. XmlNode node = result.CreateXmlDeclaration("1.0", "utf-8", "");
  213. result.AppendChild(node);
  214. //创建根节点
  215. XmlNode root = result.CreateElement("XmlText");
  216. result.AppendChild(root);
  217. XmlNode Modeltext = result.CreateElement("Model");
  218. root.AppendChild(Modeltext);
  219. CreateNode(result, Modeltext, "value", MessageValue);
  220. }
  221. catch
  222. {
  223. //MessageBox.Show("配置文件异常");
  224. }
  225. result.Save(XmlPath);//生成加密后的XML文件
  226. }
  227. /// <summary>
  228. /// 秘钥解密
  229. /// </summary>
  230. /// <param name="XmlPath"></param>
  231. private void XmlDecrypt(string XmlPath)
  232. {
  233. XElement result = XElement.Parse("<value></value>");
  234. string XmlTextValue = string.Empty;
  235. XmlDocument xmlDoc = new XmlDocument();
  236. xmlDoc.PreserveWhitespace = true;
  237. XElement xe = XElement.Load(XmlPath);
  238. IEnumerable<XElement> elements = from ele in xe.Elements("Model") select ele;
  239. //读取Xml文件并解密
  240. foreach (var ele in elements)
  241. {
  242. try
  243. {
  244. XmlTextValue = Convert.ToString(ele.Element("value").Value);
  245. //xe = XmlDecrypt(XmlTextValue);
  246. }
  247. catch
  248. {
  249. //MessageBox.Show("配置文件异常");
  250. return;
  251. }
  252. }
  253. //分析解密后的数据
  254. if (string.IsNullOrEmpty(XmlTextValue)) return;
  255. try
  256. {
  257. Byte[] toEncryptArray = Convert.FromBase64String(XmlTextValue);
  258. RijndaelManaged rm = new RijndaelManaged
  259. {
  260. Key = Encoding.UTF8.GetBytes(XmlEncryptionString),
  261. Mode = CipherMode.ECB,
  262. Padding = PaddingMode.PKCS7
  263. };
  264. ICryptoTransform cTransform = rm.CreateDecryptor();
  265. Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
  266. XmlTextValue = Encoding.UTF8.GetString(resultArray);
  267. result = XElement.Parse(XmlTextValue);
  268. result.Save(path);
  269. }
  270. catch
  271. {
  272. //MessageBox.Show("配置文件异常");
  273. }
  274. }
  275. /// <summary>
  276. /// 创建节点
  277. /// </summary>
  278. /// <param name="xmldoc"></param> xml文档
  279. /// <param name="parentnode"></param>父节点
  280. /// <param name="name"></param> 节点名
  281. /// <param name="value"></param> 节点值
  282. private void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
  283. {
  284. XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
  285. node.InnerText = value;
  286. parentNode.AppendChild(node);
  287. }
  288. }
  289. }