using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Security.Cryptography;
using System.Text;
using System.Threading.Tasks;
using System.Xml;
using System.Xml.Linq;
using System.Xml.Serialization;
namespace XmlClass
{
public class ModelXmlReadWrite
{
private static readonly ModelXmlReadWrite modelXmlReadWrite = new ModelXmlReadWrite();
private string XmlEncryptionString = "jiuzhankejijiami";
string path = AppDomain.CurrentDomain.SetupInformation.ApplicationBase + "Config.xml";
private ModelXmlReadWrite() { }
public static ModelXmlReadWrite GetModelXmlReadWrite()
{
return modelXmlReadWrite;
}
///
/// 封装一个继承StringWrite的方法(可定义Encoding)
///
public sealed class StringWriterWithEncoding : StringWriter
{
private readonly Encoding encoding;
public StringWriterWithEncoding(Encoding encoding)
{
this.encoding = encoding;
}
public override Encoding Encoding
{
get
{
return encoding;
}
}
}
///
/// 写入Xml
/// 使用方法 WriteXml(Model)
///
///
///
public string WriteXml(object obj)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
string content = string.Empty;
//序列化
using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(writer, obj);
content = writer.ToString();
}
//保存文件
using (StreamWriter stream_writer = new StreamWriter(path, false, Encoding.UTF8))
{
stream_writer.Write(content);
}
return content;
}
///
/// 写入Xml,带路径
/// 使用方法 WriteXml(Model)
///
///
///
public string WriteXml(object obj,string WXPath)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
string content = string.Empty;
//序列化
using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(writer, obj);
content = writer.ToString();
}
//保存文件
using (StreamWriter stream_writer = new StreamWriter(WXPath, false, Encoding.UTF8))
{
stream_writer.Write(content);
}
return content;
}
///
/// 写入Xml(带加密)
///
/// Model值
/// 是否加密
///
public string WriteXml(object obj,bool IsEncryption)
{
XmlSerializer serializer = new XmlSerializer(obj.GetType());
string content = string.Empty;
//序列化
using (StringWriterWithEncoding writer = new StringWriterWithEncoding(Encoding.UTF8))
{
serializer.Serialize(writer, obj);
content = writer.ToString();
}
//保存文件
using (StreamWriter stream_writer = new StreamWriter(path, false, Encoding.UTF8))
{
stream_writer.Write(content);
}
if (IsEncryption)
{
XmlEncryption(path);
}
return content;
}
///
/// 读取Xml
/// 使用方法 Model=(Model)ReadXml(typeof(Model))
///
/// typeof(Model)
///
public object ReadXml(Type object_type,string XRPath)
{
XmlSerializer serializer = new XmlSerializer(object_type);
using (StreamReader reader = new StreamReader(XRPath, Encoding.UTF8))
{
//反序列化
return serializer.Deserialize(reader);
}
}
///
/// 读取Xml
/// 使用方法 Model=(Model)ReadXml(typeof(Model))
///
/// typeof(Model)
///
public object ReadXml(Type object_type)
{
XmlSerializer serializer = new XmlSerializer(object_type);
using (StreamReader reader = new StreamReader(path,Encoding.UTF8))
{
//反序列化
return serializer.Deserialize(reader);
}
}
///
/// 读取Xml
/// 使用方法 Model=(Model)ReadXml(typeof(Model))
///
///
///
///
public object ReadXml(Type object_type, bool IsEncryption)
{
object result = null;
if (IsEncryption)
{
XmlDecrypt(path);
}
XmlSerializer serializer = new XmlSerializer(object_type);
using (StreamReader reader = new StreamReader(path, Encoding.UTF8))
{
result = serializer.Deserialize(reader);
//反序列化
}
if (IsEncryption)
{
XmlEncryption(path);
}
return result;
}
public bool CheckConfigDafaultPath()
{
bool result = false;
try
{
if(File.Exists(path))
{
result = true;
}
}
catch
{
}
return result;
}
///
/// Xml秘钥加密
///
///
private void XmlEncryption(string XmlPath)
{
string XmlText = "";
XmlDocument xmlDoc = new XmlDocument();
XmlDocument result = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
xmlDoc.Load(XmlPath);//加载要加密的XML文件
XmlText = xmlDoc.InnerXml;
if (string.IsNullOrEmpty(XmlText)) return;
try
{
Byte[] toEncryptArray = Encoding.UTF8.GetBytes(XmlText);
RijndaelManaged rm = new RijndaelManaged
{
//设置密钥:key为32位=数字或字母16个=汉字8个
Key = Encoding.UTF8.GetBytes(XmlEncryptionString),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateEncryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
string MessageValue = Convert.ToBase64String(resultArray, 0, resultArray.Length);
//创建类型声明节点
XmlNode node = result.CreateXmlDeclaration("1.0", "utf-8", "");
result.AppendChild(node);
//创建根节点
XmlNode root = result.CreateElement("XmlText");
result.AppendChild(root);
XmlNode Modeltext = result.CreateElement("Model");
root.AppendChild(Modeltext);
CreateNode(result, Modeltext, "value", MessageValue);
}
catch
{
//MessageBox.Show("配置文件异常");
}
result.Save(XmlPath);//生成加密后的XML文件
}
///
/// 秘钥解密
///
///
private void XmlDecrypt(string XmlPath)
{
XElement result = XElement.Parse("");
string XmlTextValue = string.Empty;
XmlDocument xmlDoc = new XmlDocument();
xmlDoc.PreserveWhitespace = true;
XElement xe = XElement.Load(XmlPath);
IEnumerable elements = from ele in xe.Elements("Model") select ele;
//读取Xml文件并解密
foreach (var ele in elements)
{
try
{
XmlTextValue = Convert.ToString(ele.Element("value").Value);
//xe = XmlDecrypt(XmlTextValue);
}
catch
{
//MessageBox.Show("配置文件异常");
return;
}
}
//分析解密后的数据
if (string.IsNullOrEmpty(XmlTextValue)) return;
try
{
Byte[] toEncryptArray = Convert.FromBase64String(XmlTextValue);
RijndaelManaged rm = new RijndaelManaged
{
Key = Encoding.UTF8.GetBytes(XmlEncryptionString),
Mode = CipherMode.ECB,
Padding = PaddingMode.PKCS7
};
ICryptoTransform cTransform = rm.CreateDecryptor();
Byte[] resultArray = cTransform.TransformFinalBlock(toEncryptArray, 0, toEncryptArray.Length);
XmlTextValue = Encoding.UTF8.GetString(resultArray);
result = XElement.Parse(XmlTextValue);
result.Save(path);
}
catch
{
//MessageBox.Show("配置文件异常");
}
}
///
/// 创建节点
///
/// xml文档
/// 父节点
/// 节点名
/// 节点值
private void CreateNode(XmlDocument xmlDoc, XmlNode parentNode, string name, string value)
{
XmlNode node = xmlDoc.CreateNode(XmlNodeType.Element, name, null);
node.InnerText = value;
parentNode.AppendChild(node);
}
}
}