123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579 |
- using System;
- using System.Text;
- using System.Xml;
- using System.Xml.Serialization;
- using System.IO;
- using System.Runtime.Serialization.Formatters.Binary;
- using System.Globalization;
- using System.IO.Compression;
- namespace BaseLibRWFile
- {
- /// <summary>
- /// XMLHelper
- /// </summary>
- public class XMLHelper
- {
- /// <summary>
- /// Creates the specified node name.
- /// </summary>
- /// <param name="nodeName">Name of the node.</param>
- /// <returns>XmlNode.</returns>
- public static XmlNode Create(string nodeName)
- {
- var doc = new XmlDocument();
- XmlNode node = doc.CreateElement(nodeName);
- return node;
- }
- /// <summary>
- /// Creates the attribute.
- /// </summary>
- /// <param name="node">The node.</param>
- /// <param name="attributeName">Name of the attribute.</param>
- /// <param name="value">The value.</param>
- /// <returns>XmlAttribute.</returns>
- public static XmlAttribute CreateAttribute(XmlNode node, string attributeName, string value)
- {
- try
- {
- XmlDocument doc = node.OwnerDocument;
- XmlAttribute attr = doc.CreateAttribute(attributeName);
- attr.Value = value;
- node.Attributes.SetNamedItem(attr);
- return attr;
- }
- catch (Exception err)
- {
- string desc = err.Message;
- return null;
- }
- }
- /// <summary>
- /// Objects to XML.
- /// </summary>
- /// <param name="config">The configuration.</param>
- /// <returns>XmlNode.</returns>
- public static XmlNode ObjectToXML(object config)
- {
- try
- {
- var xnd = new XmlDocument();
- if (config != null)
- {
- //we need the type to serialize
- Type t = config.GetType();
- var ser = new XmlSerializer(t);
- //will hold the xml
- using (var writer = new StringWriter(CultureInfo.InvariantCulture))
- {
- ser.Serialize(writer, config);
- xnd.LoadXml(writer.ToString());
- writer.Close();
- }
- }
- return xnd.DocumentElement;
- }
- catch
- {
- throw;
- }
- }
- /// <summary>
- /// XMLs to object.
- /// </summary>
- /// <param name="node">The node.</param>
- /// <param name="objectType">Type of the object.</param>
- /// <returns>System.Object.</returns>
- public static object XMLToObject(XmlNode node, Type objectType)
- {
- object convertedObject = null;
- if (node != null)
- {
- using (var reader = new StringReader(node.OuterXml))
- {
- var ser = new XmlSerializer(objectType);
- convertedObject = ser.Deserialize(reader);
- reader.Close();
- }
- }
- return convertedObject;
- }
- }
- /// <summary>
- /// Class XmlSerializerHelper.
- /// </summary>
- public class ClsXml
- {
- /// <summary>
- /// 读取XML文件
- /// </summary>
- /// <param name="XmlFilePath">The XML file path.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- public static object ReadXML(string XmlFilePath, Type type)
- {
- object object4Read = null;
- var serializer = new XmlSerializer(type);
- if (!File.Exists(XmlFilePath))
- {
- return new object();
- }
- while (object4Read == null)
- {
- var stream = new FileStream(XmlFilePath, FileMode.Open);
- try
- {
- object4Read = serializer.Deserialize(stream);
- }
- finally
- {
- stream.Close();
- }
- }
- return object4Read;
- }
- /// <summary>
- /// 序列化XML文件
- /// </summary>
- /// <param name="myDs">My ds.</param>
- /// <param name="XmlFilePath">The XML file path.</param>
- /// <param name="type">The type.</param>
- /// <returns><c>true</c> if XXXX, <c>false</c> otherwise.</returns>
- public static bool WriteXML(object myDs, string XmlFilePath, Type type)
- {
- bool flag = true;
- StreamWriter writer = null;
- var serializer = new XmlSerializer(type);
- try
- {
- writer = new StreamWriter(XmlFilePath, false);
- serializer.Serialize(writer, myDs);
- }
- catch (Exception)
- {
- flag = false;
- }
- finally
- {
- if (writer != null)
- {
- writer.Close();
- }
- }
- return flag;
- }
- /// <summary>
- /// XMLs the serialize.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="entity">The entity.</param>
- /// <returns>System.String.</returns>
- public static string XMLSerialize<T>(T entity)
- {
- var buffer = new StringBuilder();
- var serializer = new XmlSerializer(typeof(T));
- using (TextWriter writer = new StringWriter(buffer))
- {
- serializer.Serialize(writer, entity);
- }
- return buffer.ToString();
- }
- /// <summary>
- /// Des the XML serialize.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="xmlString">The XML string.</param>
- /// <returns>T.</returns>
- public static T DeXMLSerialize<T>(string xmlString)
- {
- T cloneObject = default(T);
- var buffer = new StringBuilder();
- buffer.Append(xmlString);
- var serializer = new XmlSerializer(typeof(T));
- using (TextReader reader = new StringReader(buffer.ToString()))
- {
- Object obj = serializer.Deserialize(reader);
- cloneObject = (T)obj;
- }
- return cloneObject;
- }
- /// <summary>
- /// 把对象序列化为字符串
- /// </summary>
- /// <param name="pObj">The p object.</param>
- /// <returns>System.Byte[].</returns>
- public static byte[] SerializeObject(object pObj)
- {
- if (pObj == null)
- return null;
- var _memory = new MemoryStream();
- var formatter = new BinaryFormatter();
- formatter.Serialize(_memory, pObj);
- _memory.Position = 0;
- var read = new byte[_memory.Length];
- _memory.Read(read, 0, read.Length);
- _memory.Close();
- return Compress(read);
- }
- /// <summary>
- /// 把字节反序列化成相应的对象
- /// </summary>
- /// <param name="pBytes">字节流</param>
- /// <returns>object</returns>
- public static object DeserializeObject(byte[] pBytes)
- {
- object _newOjb = null;
- if (pBytes == null)
- return _newOjb;
- var _memory = new MemoryStream(Decompress(pBytes));
- _memory.Position = 0;
- var formatter = new BinaryFormatter();
- _newOjb = formatter.Deserialize(_memory);
- _memory.Close();
- return _newOjb;
- }
- /// <summary>
- /// Write byte[] to file
- /// </summary>
- /// <param name="dataSource">The data source.</param>
- /// <param name="filePath">The file path.</param>
- public static void WriteByteToFile(byte[] dataSource, string filePath)
- {
- var fs = new FileStream(filePath, FileMode.Create);
- //将byte数组写入文件中
- fs.Write(dataSource, 0, dataSource.Length);
- fs.Close();
- }
- /// <summary>
- /// Read byte from file
- /// </summary>
- /// <param name="filePath">The file path.</param>
- /// <returns>System.Byte[].</returns>
- public static byte[] ReadByteFromFile(string filePath)
- {
- var fs = new FileStream(filePath, FileMode.Open);
- //获取文件大小
- long size = fs.Length;
- var array = new byte[size];
- //将文件读到byte数组中
- fs.Read(array, 0, array.Length);
- fs.Close();
- return array;
- }
- /// <summary>
- /// Write object to file
- /// </summary>
- /// <param name="dataSource">The data source.</param>
- /// <param name="filePath">The file path.</param>
- public static void WriteObjectToFile(object dataSource, string filePath)
- {
- var fs = new FileStream(filePath, FileMode.Create);
- byte[] arraysource = SerializeObject(dataSource);
- //将byte数组写入文件中
- fs.Write(arraysource, 0, arraysource.Length);
- fs.Close();
- }
- /// <summary>
- /// Read object from file
- /// </summary>
- /// <param name="filePath">The file path.</param>
- /// <returns>System.Object.</returns>
- public static object ReadObjectFromFile(string filePath)
- {
- var fs = new FileStream(filePath, FileMode.Open);
- //获取文件大小
- long size = fs.Length;
- var array = new byte[size];
- //将文件读到byte数组中
- fs.Read(array, 0, array.Length);
- fs.Close();
- return DeserializeObject(array);
- }
- /// <summary>
- /// 字符串压缩
- /// </summary>
- /// <param name="data">The data.</param>
- /// <returns>System.Byte[].</returns>
- /// <exception cref="Exception"></exception>
- public static byte[] Compress(byte[] data)
- {
- try
- {
- var ms = new MemoryStream();
- var zip = new GZipStream(ms, CompressionMode.Compress, true);
- zip.Write(data, 0, data.Length);
- zip.Close();
- var buffer = new byte[ms.Length];
- ms.Position = 0;
- ms.Read(buffer, 0, buffer.Length);
- ms.Close();
- return buffer;
- }
- catch (Exception e)
- {
- throw new Exception(e.Message);
- }
- }
- /// <summary>
- /// 字符串解压缩
- /// </summary>
- /// <param name="data">The data.</param>
- /// <returns>System.Byte[].</returns>
- /// <exception cref="Exception"></exception>
- public static byte[] Decompress(byte[] data)
- {
- try
- {
- var ms = new MemoryStream(data);
- var zip = new GZipStream(ms, CompressionMode.Decompress, true);
- var msreader = new MemoryStream();
- var buffer = new byte[0x1000];
- while (true)
- {
- int reader = zip.Read(buffer, 0, buffer.Length);
- if (reader <= 0)
- {
- break;
- }
- msreader.Write(buffer, 0, reader);
- }
- zip.Close();
- ms.Close();
- msreader.Position = 0;
- buffer = msreader.ToArray();
- msreader.Close();
- return buffer;
- }
- catch (Exception e)
- {
- throw new Exception(e.Message);
- }
- }
- /// <summary>
- /// string 压缩
- /// </summary>
- /// <param name="str">The string.</param>
- /// <returns>System.String.</returns>
- public static string CompressString(string str)
- {
- string compressString = "";
- byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
- byte[] compressAfterByte = Compress(compressBeforeByte);
- //compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
- compressString = Convert.ToBase64String(compressAfterByte);
- return compressString;
- }
- /// <summary>
- /// string 解压缩
- /// </summary>
- /// <param name="str">The string.</param>
- /// <returns>System.String.</returns>
- public static string DecompressString(string str)
- {
- string compressString = "";
- //byte[] compressBeforeByte = Encoding.GetEncoding("UTF-8").GetBytes(str);
- byte[] compressBeforeByte = Convert.FromBase64String(str);
- byte[] compressAfterByte = Decompress(compressBeforeByte);
- compressString = Encoding.GetEncoding("UTF-8").GetString(compressAfterByte);
- return compressString;
- }
- /// <summary>
- /// XMLs the serialize internal.
- /// </summary>
- /// <param name="stream">The stream.</param>
- /// <param name="o">The o.</param>
- /// <param name="encoding">The encoding.</param>
- private static void XmlSerializeInternal(Stream stream, object o, Encoding encoding)
- {
- if (o == null)
- throw new ArgumentNullException(nameof(o));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- XmlSerializer serializer = new XmlSerializer(o.GetType());
- XmlWriterSettings settings = new XmlWriterSettings();
- settings.Indent = true;
- settings.NewLineChars = "\r\n";
- settings.Encoding = encoding;
- settings.IndentChars = " ";
- using (XmlWriter writer = XmlWriter.Create(stream, settings))
- {
- serializer.Serialize(writer, o);
- writer.Close();
- }
- }
- /// <summary>
- /// 将一个对象序列化为XML字符串
- /// </summary>
- /// <param name="o">要序列化的对象</param>
- /// <param name="encoding">编码方式</param>
- /// <returns>序列化产生的XML字符串</returns>
- public static string XmlSerialize(object o, Encoding encoding)
- {
- using (MemoryStream stream = new MemoryStream())
- {
- XmlSerializeInternal(stream, o, encoding);
- stream.Position = 0;
- using (StreamReader reader = new StreamReader(stream, encoding))
- {
- return reader.ReadToEnd();
- }
- }
- }
- /// <summary>
- /// 将一个对象按XML序列化的方式写入到一个文件
- /// </summary>
- /// <param name="o">要序列化的对象</param>
- /// <param name="path">保存文件路径</param>
- /// <param name="encoding">编码方式</param>
- public static void XmlSerializeToFile(object o, string path, Encoding encoding)
- {
- if (string.IsNullOrEmpty(path))
- throw new ArgumentNullException(nameof(path));
- using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
- {
- XmlSerializeInternal(file, o, encoding);
- }
- }
- /// <summary>
- /// 从XML字符串中反序列化对象
- /// </summary>
- /// <typeparam name="T">结果对象类型</typeparam>
- /// <param name="s">包含对象的XML字符串</param>
- /// <param name="encoding">编码方式</param>
- /// <returns>反序列化得到的对象</returns>
- public static T XmlDeserialize<T>(string s, Encoding encoding)
- {
- if (string.IsNullOrEmpty(s))
- throw new ArgumentNullException(nameof(s));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- XmlSerializer mySerializer = new XmlSerializer(typeof(T));
- using (MemoryStream ms = new MemoryStream(encoding.GetBytes(s)))
- {
- using (StreamReader sr = new StreamReader(ms, encoding))
- {
- return (T)mySerializer.Deserialize(sr);
- }
- }
- }
- /// <summary>
- /// 读入一个文件,并按XML的方式反序列化对象。
- /// </summary>
- /// <typeparam name="T">结果对象类型</typeparam>
- /// <param name="path">文件路径</param>
- /// <param name="encoding">编码方式</param>
- public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
- {
- if (string.IsNullOrEmpty(path))
- throw new ArgumentNullException(nameof(path));
- if (encoding == null)
- throw new ArgumentNullException(nameof(encoding));
- string xml = File.ReadAllText(path, encoding);
- return XmlDeserialize<T>(xml, encoding);
- }
- /// <summary>
- /// XMLs the configuration writer.
- /// </summary>
- /// <typeparam name="T"></typeparam>
- /// <param name="obja">The object.</param>
- /// <param name="path">The path.</param>
- public static void XmlConfigWriter<T>(T obja, string path)
- {
- try
- {
- using (StreamWriter sw = new StreamWriter(path))
- {
- Type t = obja.GetType();
- XmlSerializer serializer = new XmlSerializer(obja.GetType());
- serializer.Serialize(sw, obja);
- sw.Close();
- }
- }
- catch (Exception e)
- {
- e.ToString();
- }
- }
- /// <summary>
- /// XMLs the configuration reader.
- /// </summary>
- /// <param name="filePath">The file path.</param>
- /// <param name="type">The type.</param>
- /// <returns>System.Object.</returns>
- public static object XmlConfigReader(string filePath, Type type)
- {
- object result = null;
- try
- {
- if (File.Exists(filePath))
- {
- using (StreamReader reader = new StreamReader(filePath))
- {
- XmlSerializer xmlSerializer = new XmlSerializer(type);
- result = xmlSerializer.Deserialize(reader);
- }
- }
- return result;
- }
- catch (Exception e)
- {
- return e;
- }
- }
- }
- }
|