C# XML与对象序列化、反序列化、泛型、zip压缩文件

1、XML序列化工具类

using System;
using System.IO;
using System.Text;
using System.Xml;
using System.Xml.Serialization;

namespace WebApplication1.App_Start
{
    public static class XmlUtil
    {
        /// <summary>
        /// 将一个对象序列化为XML字符串
        /// </summary>
        /// <param name="o">要序列化的对象</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>序列化产生的XML字符串</returns>
        public static string XmlSerialize(object o, Encoding encoding)
        {
            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            using (MemoryStream stream = new MemoryStream())
            {
                XmlSerializer serializer = new XmlSerializer(o.GetType());

                XmlWriterSettings settings = new XmlWriterSettings();
                settings.Indent = true;
                settings.NewLineChars = "\r\n";
                settings.Encoding = encoding;
                settings.IndentChars = "  ";
                settings.OmitXmlDeclaration = true;

                using (XmlWriter writer = XmlWriter.Create(stream, settings))
                {
                    //Create our own namespaces for the output
                    XmlSerializerNamespaces ns = new XmlSerializerNamespaces();
                    //Add an empty namespace and empty value
                    ns.Add("", "");
                    serializer.Serialize(writer, o, ns);
                    writer.Close();
                }

                stream.Position = 0;
                using (StreamReader reader = new StreamReader(stream, encoding))
                {
                    return reader.ReadToEnd();
                }
            }
        }

        /// <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("s");
            if (encoding == null)
                throw new ArgumentNullException("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>
        /// <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("path");
            }

            if (o == null)
            {
                throw new ArgumentNullException("o");
            }

            if (encoding == null)
            {
                throw new ArgumentNullException("encoding");
            }

            using (FileStream file = new FileStream(path, FileMode.Create, FileAccess.Write))
            {
                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(file, settings))
                {
                    serializer.Serialize(writer, o);
                    writer.Close();
                }
            }
        }

        /// <summary>
        /// 读入一个文件,并按XML的方式反序列化对象。
        /// </summary>
        /// <typeparam name="T">结果对象类型</typeparam>
        /// <param name="path">文件路径</param>
        /// <param name="encoding">编码方式</param>
        /// <returns>反序列化得到的对象</returns>
        public static T XmlDeserializeFromFile<T>(string path, Encoding encoding)
        {
            if (string.IsNullOrEmpty(path))
                throw new ArgumentNullException("path");
            if (encoding == null)
                throw new ArgumentNullException("encoding");

            string xml = File.ReadAllText(path, encoding);
            return XmlDeserialize<T>(xml, encoding);
        }
    }
}

2、泛型

    public class Test : IRequestModel
    {
        public string aaa1 { get; set; }
        public string aaa2 { get; set; }
        public string aaa3 { get; set; }
        public string aaa4 { get; set; }
        public string aaa5 { get; set; }
    }

    public interface IRequestModel
    {
    }

    [XmlRoot("CPMB2B")]
    public class RequestObj<T> where T : IRequestModel
    {
        public RequestMessageData<T> MessageData { get; set; }
    }

    public class RequestMessageData<T> where T : IRequestModel
    {
        public ModelBase Base { get; set; }
        public RequestHeader ReqHeader { get; set; }
        public T DataBody { get; set; }
    }

    public class RequestHeader
    {
        public RequestHeader() { }
        public RequestHeader(string merchantNo, string transCode, string transCodeId)
        {
            ClientTime = DateTime.Now.ToString("yyyyMMddHHmmss");
            MerchantNo = merchantNo;
            TransCode = transCode;
            TransCodeId = transCodeId;
        }
        public string ClientTime { get; set; }
        public string MerchantNo { get; set; }
        public string TransCodeId { get; set; }
        public string TransCode { get; set; }
    }

    public class ModelBase
    {
        /// <summary>
        /// 版本号,交易时要判断版本匹配
        /// </summary>
        public string Version { get; set; } = "2.3";

        /// <summary>
        /// 签名标志:0=未包含签名;1=包含签名
        /// </summary>
        public string SignFlag { get; set; } = "1";

        /// <summary>
        /// 服务模式:3=支付存管系统(PDS)
        /// </summary>
        public string SeverModel { get; set; } = "3";
    }

3、Controller

using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using System.IO;
using System.IO.Compression;
using System.Configuration;
using System.Xml.Serialization;
using WebApplication1.App_Start;
using System.Text;

namespace WebApplication1.Controllers
{
    public class DefaultController : Controller
    {
        // GET: Default
        public ActionResult Index()
        {
            try
            {
                string fileName = $@"BATCH_PAY_{DateTime.Now.ToString("yyyyMMddHHmmss")}_01.DAT";

                RequestObj<Test> a = new RequestObj<Test>();
                a.MessageData = new RequestMessageData<Test>();
                a.MessageData.Base = new ModelBase();
                a.MessageData.DataBody = new Test
                {
                    aaa1 = "1",
                    aaa2 = "2",
                    aaa3 = "3",
                    aaa4 = "4"
                };

                string xml = XmlUtil.XmlSerialize(a, Encoding.UTF8);

                WriteFile(fileName, "test test");

                string filePath = $@"{WebRoot()}DAT\{fileName}";
                string datPath = $@"{WebRoot()}DAT";
                string zipPath = $@"D:\web\zip\{fileName}.zip";
                string extractPath = @"D:\MyFile\example";

                //将整个文件夹压缩为ZIP文件 
                ZipFile.CreateFromDirectory(datPath, zipPath);
                System.IO.File.Delete(filePath);

                //读取压缩文件信息
                if (System.IO.File.Exists(zipPath))
                {
                    var data = ZipFile.OpenRead(zipPath);
                    using (var stream = data.Entries[0].Open())
                    {
                        using (StreamReader sr = new StreamReader(stream))
                        {
                            var str = sr.ReadToEnd();
                            var list = str.Split(Environment.NewLine.ToCharArray()).ToList();
                        }
                    }
                }

                //解压ZIP文件到extrat目录中。 
                //ZipFile.ExtractToDirectory(zipPath, extractPath);
            }
            catch (Exception ex)
            {
                throw ex;
            }
            return View();
        }


        public void WriteFile(string fileName, string content)
        {
            string path = string.Empty;
            var current = System.Web.HttpContext.Current;
            //在网站根目录下创建日志目录 
            if (current == null)
                path = ConfigurationManager.AppSettings["WebLogPath"].ToString();
            else
                path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath + "DAT";
            if (!Directory.Exists(path))//如果日志目录不存在就创建  
            {
                Directory.CreateDirectory(path);
            }
            string filePath = $"{path}/{fileName}";//用日期对日志文件命名  
            string time = DateTime.Now.ToString("yyyy-MM-dd HH:mm:ss.fff");//获取当前系统时间  

            //创建或打开日志文件,向日志文件末尾追加记录  
            using (StreamWriter mySw = System.IO.File.AppendText(filePath))
            {
                //向日志文件写入内容  
                string write_content = time + " " + content;
                mySw.WriteLine(write_content);

                //关闭日志文件  
                mySw.Close();
            }
        }

        public string WebRoot()
        {
            string path = string.Empty;
            var current = System.Web.HttpContext.Current;
            //在网站根目录下创建日志目录 
            if (current == null)
                path = ConfigurationManager.AppSettings["WebLogPath"].ToString();
            else
                path = System.Web.HttpContext.Current.Request.PhysicalApplicationPath;
            if (!Directory.Exists(path))//如果日志目录不存在就创建  
            {
                Directory.CreateDirectory(path);
            }

            return path;
        }
    }
}


4、


5、


6、


7、


8、

猜你喜欢

转载自blog.csdn.net/KingCruel/article/details/89496451