• C# 通过xml模板组装xml数据


    1.xml模板存放路径

    <?xml version="1.0" encoding="UTF-8"?>
    <!--新增中标(成交)结果公告-->
    
    <DESCONTEXT>
      <WIN_BID_PRICE></WIN_BID_PRICE>
      <WINNINGBIDDER_TYPE></WINNINGBIDDER_TYPE>
      <PRICE_FORM_CODE>价款 </PRICE_FORM_CODE>
      <WIN_BID_RATE>中标</WIN_BID_RATE>
      <REGION_CODE>采购 </REGION_CODE>
      <TRA_PLACE_CODE>交易 </TRA_PLACE_CODE>
      <PURCHASER_AGENCY_NAME>采购 </PURCHASER_AGENCY_NAME>
      <PURCHASER_AGENCY_CODE>采购 </PURCHASER_AGENCY_CODE>
      <PURCHASE_PROJECT_CODE>采购</PURCHASE_PROJECT_CODE>
      <PURCHASE_PROJECT_NAME>采购</PURCHASE_PROJECT_NAME>
      <PURCHASE_SECTION_CODE>采购</PURCHASE_SECTION_CODE>
      <UNIFIED_DEAL_CODE></UNIFIED_DEAL_CODE>
      <WIN_BID_BULLETIN_TITLE></WIN_BID_BULLETIN_TITLE>
      <WIN_BID_BULLETIN_CONTENT></WIN_BID_BULLETIN_CONTENT>
      <WIN_BID_BULLETIN_START_TIME></WIN_BID_BULLETIN_START_TIME>
      <URL>公告L</URL>
      <WINNINGBIDDER_NAME></WINNINGBIDDER_NAME>
      <WINNINGBIDDER_CODE></WINNINGBIDDER_CODE>
      <CURRENCY_CODE></CURRENCY_CODE>
      <PRICE_UNIT>价位</PRICE_UNIT>
      <CREATOR>建人</CREATOR>
      <PLATFORM_CODE>交码</PLATFORM_CODE>
      <PUB_SERVICE_PLAT_CODE>识码</PUB_SERVICE_PLAT_CODE>
      <DATA_TIMESTAMP></DATA_TIMESTAMP>
    </DESCONTEXT>
    Xml模板
    public partial class S_ZPURCHASEBID
        {
              
            /// <summary>
            ////// </summary>
            public string PURCHASE_PROJECT_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string PURCHASE_PROJECT_NAME { get; set; }
            /// <summary>
            ////// </summary>
            public string PURCHASE_SECTION_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string UNIFIED_DEAL_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string WIN_BID_BULLETIN_TITLE { get; set; }
            /// <summary>
            ////// </summary>
            public string WIN_BID_BULLETIN_CONTENT { get; set; }
            /// <summary>
            ////// </summary>
            public Nullable<System.DateTime> WIN_BID_BULLETIN_START_TIME { get; set; }
            /// <summary>
            ////// </summary>
            public string URL { get; set; }
            /// <summary>
            ////// </summary>
            public string WINNINGBIDDER_NAME { get; set; }
            /// <summary>
            ////// </summary>
            public string WINNINGBIDDER_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public Nullable<float> WIN_BID_PRICE { get; set; }
            /// <summary>
            ////// </summary>
            public string CURRENCY_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string PRICE_UNIT { get; set; }
            /// <summary>
            ////// </summary>
            public string CREATOR { get; set; }
            /// <summary>
            /// 【附件】 
            /// </summary>
            //public string ATTACHMENT_SET_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string PLATFORM_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string PUB_SERVICE_PLAT_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public Nullable<System.DateTime> DATA_TIMESTAMP { get; set; }
       
            /// <summary>
            ////// </summary>
            public string REGION_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string TRA_PLACE_CODE { get; set; }
            /// <summary>
            ////// </summary>
            public string PURCHASER_AGENCY_NAME { get; set; }
            /// <summary>
            ////// </summary>
            public string PURCHASER_AGENCY_CODE { get; set; }
            /// <summary>
            /// /中
            /// </summary>
            public string WINNINGBIDDER_TYPE { get; set; }
            /// <summary>
            /// 价)
            /// </summary>
            public string PRICE_FORM_CODE { get; set; }
            public string WIN_BID_RATE { get; set; }
            public virtual S_ZPURCHASEPROJECT S_ZPURCHASEPROJECT { get; set; }
        }
    S_ZPURCHASEBID类
    using Bobole.Common;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Reflection;
    using System.Web;
    using System.Xml;
    
    /// <summary>
    /// NUtils 的摘要说明
    /// </summary>
    public class NUtils
    {
        /// <summary>
        /// 上报保存zip文件
        /// </summary>
        /// <param name="code">编码</param>
        /// <param name="oldData">原始xml数据源"/DataReportTemplate/DataModel.xml"</param>
        /// <param name="dataModel">公用xml模型地址</param>
        /// <param name="FilePath">文件存放路径"~/ToprovinceFile/File"</param>
        /// <param name="OutFilePath">文件输出路径"~/ToprovinceFile/OutFile/"</param>
        public static bool CreateFile(XmlDataDocument oldData, string code, out XmlDataDocument Data, out string dirp, out string outpath, Dictionary<string, string> dic, out Dictionary<string, string> outError,out string Data_Key,out string Data_NO)
        {
            Data_Key = "";
            Data_NO = "";
            var dataModel = ConfigurationManager.AppSettings["DataModel"];
            var FilePath = ConfigurationManager.AppSettings["NewFilePath"];
            var OutFilePath = ConfigurationManager.AppSettings["OutFilePath"];
            var CodeFilePath = ConfigurationManager.AppSettings["CodeModel"];
            var boolResult = true;
            outError = new Dictionary<string, string>();
            string FileName = "";
            try
            {
                //创建文件夹
                string FullPath = FileZip(Common.MapPath(FilePath), code, out FileName);
                string DirPath = FullPath;
                //向FullPath下保存文件
                //创建xml文件 
                XmlDataDocument fileDoc = new XmlDataDocument();
                fileDoc.Load(Common.MapPath(dataModel));
                var fileNode = fileDoc.SelectSingleNode("/ROOT/HEADDATA").Clone();
                fileDoc.SelectSingleNode("/ROOT").RemoveAll();
                XmlNode newFileNode = fileNode.Clone();
                XmlDataDocument jyModel = new XmlDataDocument();
                jyModel.Load(Common.MapPath(CodeFilePath + "/" + code + ".xml"));
                newFileNode.SelectSingleNode("/FROMPLATFORMCODE").InnerText = ConfigurationManager.AppSettings["FROMPLATFORMCODE"];
                newFileNode.SelectSingleNode("/TOPLATFORMCODE").InnerText = ConfigurationManager.AppSettings["TOPLATFORMCODE"];
                Data_NO = jyModel.SelectSingleNode("/des/title/DATA_NO").InnerText;
                newFileNode.SelectSingleNode("/DATA_NO").InnerText = Data_NO;
                newFileNode.SelectSingleNode("/DATA_EN").InnerText = jyModel.SelectSingleNode("/des/title/DATA_EN").InnerText; ;
                newFileNode.SelectSingleNode("/DATA_CN").InnerText = jyModel.SelectSingleNode("/des/title/DATA_CH").InnerText; ;
                newFileNode.SelectSingleNode("/DATA_TYPE").InnerText = "1";//数据类型(1 新增,2 修改,3 删除)
                Data_Key = Guid.NewGuid().ToString();
                newFileNode.SelectSingleNode("/DATA_KEY").InnerText = Data_Key;
                newFileNode.SelectSingleNode("/TIMESTAMP").InnerText = DateTime.Now.ToString("yyyyMMddhhmmss");
                newFileNode.SelectSingleNode("/VERSION").InnerText = "2.0"; 
                fileDoc.SelectSingleNode("/ROOT").AppendChild(newFileNode);
                //Import the last book node from doc2 into the original document. 
                XmlNode newBook = fileDoc.ImportNode(oldData.DocumentElement, true);
                
                //检查数据是否符合规范 
                fileDoc.SelectSingleNode("/ROOT").AppendChild(newBook);
                //加附件节点
                XmlNode nodeDESBINARYS = fileDoc.CreateElement("DESBINARYS");
                fileDoc.SelectSingleNode("/ROOT").AppendChild(nodeDESBINARYS);
                Data = fileDoc;
                dirp = DirPath;
                outpath = Common.MapPath(OutFilePath + FileName + ".zip");
                //校验文件是否合格
                XmlDataDocument dicdata = new XmlDataDocument();
                dicdata.Load(Common.MapPath(CodeFilePath + "/dic.xml"));
                if (IsCanReport(jyModel, newBook, dicdata, out outError))
                {
                    boolResult = false;
                    if (Directory.Exists(FullPath))
                    {
                        DelectDir(FullPath);
                        Directory.Delete(FullPath);
                    }
                }
                if (boolResult)
                {
                    File.WriteAllText(DirPath + "\" + FileName + ".xml", fileDoc.InnerXml);
                    boolResult = true;
                }
            }
            catch (Exception)
            {
                if (Directory.Exists(FileName))
                {
                    DelectDir(FileName);
                }
                Data = new XmlDataDocument();
                dirp = "";
                outpath = "";
                boolResult = false;
            }
            return boolResult;
        }
        /// <summary>
        /// 删除文件包括子目录
        /// </summary>
        /// <param name="srcPath"></param>
        public static void DelectDir(string srcPath)
        {
            try
            {
                DirectoryInfo dir = new DirectoryInfo(srcPath);
                FileSystemInfo[] fileinfo = dir.GetFileSystemInfos();  //返回目录中所有文件和子目录
                foreach (FileSystemInfo i in fileinfo)
                {
                    if (i is DirectoryInfo)            //判断是否文件夹
                    {
                        DirectoryInfo subdir = new DirectoryInfo(i.FullName);
                        subdir.Delete(true);          //删除子目录和文件
                    }
                    else
                    {
                        File.Delete(i.FullName);      //删除指定文件
                    }
                }
            }
            catch (Exception e)
            {
                throw;
            }
        }
    
        /// <summary>
        /// 拼接xml
        /// </summary>
        /// <param name="data"></param>
        /// <param name="xmlFile">xml文件路径 相对路径</param>
        /// <param name="xmlnodePath">/Data</param>
        /// <param name="Node"></param>
        public static void getXmlData(object data, string xmlFile, string xmlnodePath, out XmlDataDocument outdic)
        {
            XmlDataDocument doc = new XmlDataDocument();
            doc.Load(Common.MapPath(xmlFile));
            XmlNode dataNode = doc.SelectSingleNode(xmlnodePath);
            var nodes = dataNode.ChildNodes;
            //取到属性
            foreach (XmlElement node in nodes)
            {
                node.InnerText = "";
                PropertyInfo property = data.GetType().GetProperty(node.Name.ToUpper());
                var valtype = property.PropertyType;
                if (valtype.IsGenericType && valtype.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类  
                {
                    //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换  
                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(valtype);
                    //将type转换为nullable对的基础基元类型  
                    valtype = nullableConverter.UnderlyingType;
                }
                if (property != null)
                {
                    var value = property.GetValue(data, null);
                    if (value != null)
                        node.InnerXml = value.ToString();
                    if (valtype.Name == "DateTime")
                    {
                        DateTime dt;
                        if (DateTime.TryParse(value.ToString(), out  dt))
                        {
                            node.InnerText = dt.ToString("yyyyMMddHHmmss");
                        }
                    }
                    if (node.Name == "PROGRAM_BUDGET" || node.Name == "WIN_BID_PRICE")
                    {
                        decimal pric;
                        if (Decimal.TryParse(value.ToString(), out  pric))
                        {
                            node.InnerText = pric.ToString("0.000000");
                        }
                    }
                }
            }
            outdic = doc;
        }
        /// <summary>
        /// 拼接XML
        /// </summary>
        /// <param name="data"></param>
        /// <param name="doc"></param>
        public static void getXmlData(object data, ref XmlNode Node)
        {
            var nodes = Node.ChildNodes;
            //取到属性
            foreach (XmlElement node in nodes)
            {
                node.InnerText = "";
                PropertyInfo property = data.GetType().GetProperty(node.Name.ToUpper());
                var valtype = property.PropertyType;
                if (valtype.IsGenericType && valtype.GetGenericTypeDefinition().Equals(typeof(Nullable<>)))//判断convertsionType是否为nullable泛型类  
                {
                    //如果type为nullable类,声明一个NullableConverter类,该类提供从Nullable类到基础基元类型的转换  
                    System.ComponentModel.NullableConverter nullableConverter = new System.ComponentModel.NullableConverter(valtype);
                    //将type转换为nullable对的基础基元类型  
                    valtype = nullableConverter.UnderlyingType;
                }
                if (property != null)
                {
                    var value = property.GetValue(data, null);
                    if (value != null)
                        node.InnerText = value.ToString();
                    if (valtype.Name == "DateTime")
                    {
                        DateTime dt;
                        if (DateTime.TryParse(value.ToString(), out  dt))
                        {
                            node.InnerText = dt.ToString("yyyyMMddHHmmss");
                        }
                    }
                }
            }
    
        }
        /// <summary>
        /// 根目录
        /// </summary>
        /// <param name="inputFilePath">File</param>
        /// <returns></returns>
        public static string FileZip(string inputFilePath, string code, out string outFileName)
        {
            var timeDir = DateTime.Now.ToString("yyyyMMdd");
            string dirPath = inputFilePath + "\" + timeDir;
            if (!Directory.Exists(dirPath))
            {
                Directory.CreateDirectory(dirPath);
    
            }
            if (!Directory.Exists(dirPath + "\" + code))
            {
                Directory.CreateDirectory(dirPath + "\" + code);
            }
            //判断文件中的个数 
            DirectoryInfo TheFolder = new DirectoryInfo(dirPath + "\" + code + "\");
            var count = TheFolder.GetDirectories().Count() + 1;
            string FileName = GerFileName(timeDir, code, count + "");
            //创建文件夹
            string fullPath = dirPath + "\" + code + "\" + FileName;
    
            if (!Directory.Exists(fullPath))
            {
                Directory.CreateDirectory(fullPath);
            }
            outFileName = FileName;
    
            return fullPath;
        }
        public static string GerFileName(string timeDir, string code, string FileCount)
        {
            return timeDir + "-" + FileCount.PadLeft(6, '0') + "-" + code;
        }
        public static bool IsCanReport(XmlDataDocument jyModel, XmlNode model, XmlDataDocument dic, out Dictionary<string, string> outError)
        {
            outError = new Dictionary<string, string>();
            foreach (XmlNode item in jyModel.SelectSingleNode("/des/context").ChildNodes)
            {
                var name = model.SelectSingleNode(item.Name).InnerText;
                //验证是否为空
                if (item.SelectSingleNode("required") != null)
                {
                    var required = item.SelectSingleNode("required").InnerText;
                    if (required == "true")
                        if (string.IsNullOrEmpty(name))
                            outError.Add(item.Name, "值为空");
                }
                if (item.SelectSingleNode("lenght") != null)
                {
                    //判断定长数据
                    var required = item.SelectSingleNode("lenght").InnerText;
                    int lenght = 0;
                    int.TryParse(required, out lenght);
                    if (lenght > 0)
                        if (string.IsNullOrEmpty(name))
                            if (name.Length != lenght)
                                outError.Add(item.Name, "长度不足" + lenght);
                }
                if (item.SelectSingleNode("maxlen") != null)
                {
                    //最大长度
                    var required = item.SelectSingleNode("maxlen").InnerText;
                    int lenght = 0;
                    int.TryParse(required, out lenght);
                    if (lenght > 0)
                        if (string.IsNullOrEmpty(name))
                            if (name.Length > lenght)
                                outError.Add(item.Name, "超过了最大长度" + lenght);
                }
                if (item.SelectSingleNode("range") != null)
                {
                    //判断dic文件
                    //var required = item.SelectSingleNode("maxlen").InnerText;
                    //if (required.Contains("dic:"))
                    //{
                    //    //查询指定的数据
                    //    required = required.Replace(":", "");
                    //    string targetParm = string.Format("{0}[@value='{1}']", required, name);
                    //    var req = dic.SelectSingleNode(targetParm);
                    //    if (req == null)
                    //        a = a + 1;
                    //}
                }
            }
            return outError.Count > 0;
        }
        //检测文件是否符合规范
        public static bool IsCanReport(XmlDataDocument jyModel, XmlNode model)
        {
            int a = 0;
            //加载dic文件
            foreach (XmlNode item in jyModel.SelectSingleNode("/des/context").ChildNodes)
            {
                var name = model.SelectSingleNode(item.Name).InnerText;
                //验证是否为空
                if (item.SelectSingleNode("required") != null)
                {
                    var required = item.SelectSingleNode("required").InnerText;
                    if (required == "true")
                        if (string.IsNullOrEmpty(name))
                            a = a + 1;
                }
                if (item.SelectSingleNode("lenght") != null)
                {
                    //判断定长数据
                    var required = item.SelectSingleNode("lenght").InnerText;
                    int lenght = 0;
                    int.TryParse(required, out lenght);
                    if (lenght > 0)
                        if (string.IsNullOrEmpty(name))
                            if (name.Length != lenght)
                                a = a + 1;
                }
                if (item.SelectSingleNode("maxlen") != null)
                {
                    //最大长度
                    var required = item.SelectSingleNode("maxlen").InnerText;
                    int lenght = 0;
                    int.TryParse(required, out lenght);
                    if (lenght > 0)
                        if (string.IsNullOrEmpty(name))
                            if (name.Length > lenght)
                                a = a + 1;
                }
                if (item.SelectSingleNode("range") != null)
                {
                    //判断dic文件
                    var required = item.SelectSingleNode("maxlen").InnerText;
                    if (required.Contains("dic:"))
                    {
                        //查询指定的数据
                        required.Replace(":", "");
                    }
                }
            }
            return a > 0;
        }
        /// <summary>
        /// 获取文件夹名称 (/XX/XX)
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static string GetFileName(string code)
        {
            string DirectoryName = "";
            DirectoryName = DateTime.Now.ToString("yyyyMMdd") + "-" + "" + "-" + code;
            return "";
        }
    
        /// <summary>
        /// 检查文件夹是否存在 如果存在则返回true 不存在将创建
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static bool ExistsDirectory(string FilePath)
        {
            if (Directory.Exists(FilePath) == false)
            {
                Directory.CreateDirectory(FilePath);
            }
            return true;
        }
        /// <summary>
        /// 验证统一信用代码
        /// </summary>
        /// <param name="code"></param>
        /// <returns></returns>
        public static bool CheckSocialCreditCode(string code)
        {
            if (code == null || code.Length != 18) return false;
            code = code.ToUpper(); int[] factor = { 1, 3, 9, 27, 19, 26, 16, 17, 20, 29, 25, 13, 8, 24, 10, 30, 28 };
            string str = "0123456789ABCDEFGHJKLMNPQRTUWXY";
            int total = factor.Select((p, i) => p * str.IndexOf(code[i])).Sum();
            int index = total % 31 == 0 ? 0 : (31 - total % 31); return str[index] == code.Last();
        }
        /// <summary>
        /// 判断文件是否存在
        /// </summary>
        /// <param name="FilePath"></param>
        /// <returns></returns>
        public static bool ExcelFiel(string FilePath)
        {
            return File.Exists(FilePath);
        }
    }
    NUtils帮助类
    using ICSharpCode.SharpZipLib.Checksums;
    using ICSharpCode.SharpZipLib.Zip;
    using System;
    using System.Collections.Generic;
    using System.Configuration;
    using System.IO;
    using System.Linq;
    using System.Web;
    
    /// <summary>
    /// ZipHelper 的摘要说明
    /// </summary>
    public class ZipHelper
    {
        public ZipHelper()
        {
    
        }
        #region 私有方法
        /// <summary>
        /// 递归压缩文件夹方法
        /// </summary>
        private static bool ZipFileDictory(string FolderToZip, ZipOutputStream s, string ParentFolderName)
        {
            bool res = true;
            string[] folders, filenames;
            ZipEntry entry = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
            try
            {
                entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/"));
                s.PutNextEntry(entry);
                s.Flush();
                filenames = Directory.GetFiles(FolderToZip);
                foreach (string file in filenames)
                {
                    fs = File.OpenRead(file);
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    entry = new ZipEntry(Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip) + "/" + Path.GetFileName(file)));
                    entry.DateTime = DateTime.Now;
                    entry.Size = fs.Length;
                    fs.Close();
                    crc.Reset();
                    crc.Update(buffer);
                    entry.Crc = crc.Value;
                    s.PutNextEntry(entry);
                    s.Write(buffer, 0, buffer.Length);
                }
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs = null;
                }
                if (entry != null)
                {
                    entry = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            folders = Directory.GetDirectories(FolderToZip);
            foreach (string folder in folders)
            {
                if (!ZipFileDictory(folder, s, Path.Combine(ParentFolderName, Path.GetFileName(FolderToZip))))
                {
                    return false;
                }
            }
            return res;
        }
        /// <summary>
        /// 压缩目录
        /// </summary>
        /// <param name="FolderToZip">待压缩的文件夹,全路径格式</param>
        /// <param name="ZipedFile">压缩后的文件名,全路径格式</param>
        private static bool ZipFileDictory(string FolderToZip, string ZipedFile, int level)
        {
            bool res;
            if (!Directory.Exists(FolderToZip))
            {
                return false;
            }
            ZipOutputStream s = new ZipOutputStream(File.Create(ZipedFile));
            s.SetLevel(level);
            res = ZipFileDictory(FolderToZip, s, "");
            s.Finish();
            s.Close();
            return res;
        }
        /// <summary>
        /// 压缩文件
        /// </summary>
        /// <param name="FileToZip">要进行压缩的文件名</param>
        /// <param name="ZipedFile">压缩后生成的压缩文件名</param>
        private static bool ZipFile(string FileToZip, string ZipedFile, int level)
        {
            if (!File.Exists(FileToZip))
            {
                throw new System.IO.FileNotFoundException("指定要压缩的文件: " + FileToZip + " 不存在!");
            }
            FileStream ZipFile = null;
            ZipOutputStream ZipStream = null;
            ZipEntry ZipEntry = null;
            bool res = true;
            try
            {
                ZipFile = File.OpenRead(FileToZip);
                byte[] buffer = new byte[ZipFile.Length];
                ZipFile.Read(buffer, 0, buffer.Length);
                ZipFile.Close();
    
                ZipFile = File.Create(ZipedFile);
                ZipStream = new ZipOutputStream(ZipFile);
                ZipEntry = new ZipEntry(Path.GetFileName(FileToZip));
                ZipStream.PutNextEntry(ZipEntry);
                ZipStream.SetLevel(level);
    
                ZipStream.Write(buffer, 0, buffer.Length);
            }
            catch
            {
                res = false;
            }
            finally
            {
                if (ZipEntry != null)
                {
                    ZipEntry = null;
                }
                if (ZipStream != null)
                {
                    ZipStream.Finish();
                    ZipStream.Close();
                }
                if (ZipFile != null)
                {
                    ZipFile.Close();
                    ZipFile = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
            return res;
        }
        #endregion
        /// <summary>
        /// 压缩
        /// </summary>
        /// <param name="FileToZip">待压缩的文件目录</param>
        /// <param name="ZipedFile">生成的目标文件</param>
        /// <param name="level">6</param>
        public static bool Zip(String FileToZip, String ZipedFile, int level, bool flot = false)
        {
            if (Directory.Exists(FileToZip))
            {
                flot = ConfigurationManager.AppSettings["IsFile"] == "1" ? true : false;
                //不生成文件夹 
                return ZipDirectory(FileToZip, ZipedFile, flot);
            }
            else if (File.Exists(FileToZip))
            {
                return ZipFile(FileToZip, ZipedFile, level);
            }
            else
            {
                return false;
            }
        }
        public static bool ZipDirectory(string folderToZip, string zipedFile, Boolean IncludeParent)
        {
            bool result = false;
            if (!Directory.Exists(folderToZip))
                return result;
    
            ZipOutputStream zipStream = new ZipOutputStream(File.Create(zipedFile));
            zipStream.SetLevel(6);
    
            result = ZipDirectory(folderToZip, zipStream, IncludeParent);
    
            zipStream.Finish();
            zipStream.Close();
    
            return result;
        }
        /// <summary>
        /// 私有方法,增加是否包含父文件夹方法
        /// </summary>
        /// <param name="folderToZip">要压缩的文件夹路径</param>
        /// <param name="zipStream">压缩输出流</param>
        /// <param name="ContainParent">是否包含父文件夹</param>
        /// <returns></returns>
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, Boolean ContainParent)
        {
            string[] folders, files;
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
    
            try
            {
    
                if (ContainParent)
                {
                    ent = new ZipEntry(Path.GetFileName(folderToZip) + "/");
                    zipStream.PutNextEntry(ent);
                    zipStream.Flush();
                }
    
                files = Directory.GetFiles(folderToZip);
                foreach (string file in files)
                {
                    fs = File.OpenRead(file);
    
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
    
                    if (ContainParent)
                    {
                        ent = new ZipEntry(Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file));
                    }
                    else
                    {
                        ent = new ZipEntry(Path.GetFileName(file));
                    }
    
    
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;
    
                    fs.Close();
    
                    crc.Reset();
                    crc.Update(buffer);
    
                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }
    
            }
            catch
            {
                return false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
    
    
            folders = Directory.GetDirectories(folderToZip);
    
            if (ContainParent)
            {
                foreach (string folder in folders)
                    if (!ZipDirectory(folder, zipStream, Path.GetFileName(folderToZip)))
                        return false;
            }
            else
            {
                foreach (string folder in folders)
                    if (!ZipDirectory(folder, zipStream, ""))
                        return false;
            }
    
            return true;
        }
        /// <summary>   
        /// 递归压缩文件夹的内部方法   
        /// </summary>   
        /// <param name="folderToZip">要压缩的文件夹路径</param>   
        /// <param name="zipStream">压缩输出流</param>   
        /// <param name="parentFolderName">此文件夹的上级文件夹</param>   
        /// <returns></returns>   
        private static bool ZipDirectory(string folderToZip, ZipOutputStream zipStream, string parentFolderName)
        {
            bool result = true;
            string[] folders, files;
            ZipEntry ent = null;
            FileStream fs = null;
            Crc32 crc = new Crc32();
    
            try
            {
                ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/"));
                zipStream.PutNextEntry(ent);
                zipStream.Flush();
    
                files = Directory.GetFiles(folderToZip);
                foreach (string file in files)
                {
                    fs = File.OpenRead(file);
    
                    byte[] buffer = new byte[fs.Length];
                    fs.Read(buffer, 0, buffer.Length);
                    ent = new ZipEntry(Path.Combine(parentFolderName, Path.GetFileName(folderToZip) + "/" + Path.GetFileName(file)));
                    ent.DateTime = DateTime.Now;
                    ent.Size = fs.Length;
    
                    fs.Close();
    
                    crc.Reset();
                    crc.Update(buffer);
    
                    ent.Crc = crc.Value;
                    zipStream.PutNextEntry(ent);
                    zipStream.Write(buffer, 0, buffer.Length);
                }
    
            }
            catch
            {
                result = false;
            }
            finally
            {
                if (fs != null)
                {
                    fs.Close();
                    fs.Dispose();
                }
                if (ent != null)
                {
                    ent = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
    
            folders = Directory.GetDirectories(folderToZip);
            foreach (string folder in folders)
                if (!ZipDirectory(folder, zipStream, Path.GetFileName(folderToZip)))
                    return false;
    
            return result;
        }
        /// <summary>
        /// 解压
        /// </summary>
        /// <param name="FileToUpZip">待解压的文件</param>
        /// <param name="ZipedFolder">解压目标存放目录</param>
        public static void UnZip(string FileToUpZip, string ZipedFolder)
        {
            if (!File.Exists(FileToUpZip))
            {
                return;
            }
            if (!Directory.Exists(ZipedFolder))
            {
                Directory.CreateDirectory(ZipedFolder);
            }
            ZipInputStream s = null;
            ZipEntry theEntry = null;
            string fileName;
            FileStream streamWriter = null;
            try
            {
                s = new ZipInputStream(File.OpenRead(FileToUpZip));
                while ((theEntry = s.GetNextEntry()) != null)
                {
                    if (theEntry.Name != String.Empty)
                    {
                        fileName = Path.Combine(ZipedFolder, theEntry.Name);
                        if (fileName.EndsWith("/") || fileName.EndsWith("\"))
                        {
                            Directory.CreateDirectory(fileName);
                            continue;
                        }
                        streamWriter = File.Create(fileName);
                        int size = 2048;
                        byte[] data = new byte[2048];
                        while (true)
                        {
                            size = s.Read(data, 0, data.Length);
                            if (size > 0)
                            {
                                streamWriter.Write(data, 0, size);
                            }
                            else
                            {
                                break;
                            }
                        }
                    }
                }
            }
            finally
            {
                if (streamWriter != null)
                {
                    streamWriter.Close();
                    streamWriter = null;
                }
                if (theEntry != null)
                {
                    theEntry = null;
                }
                if (s != null)
                {
                    s.Close();
                    s = null;
                }
                GC.Collect();
                GC.Collect(1);
            }
        }
    
    }
    ZipHelper 文件打包类

    2.组装数据

    XmlDataDocument doc = new XmlDataDocument();
    //组装内容
    //purchaseBid 类字段与xml类字段名称相对应
    NUtils.getXmlData(purchaseBid, @"~DataReportTemplateAddPurchaseBid.xml", @"/DESCONTEXT", out doc);
    将新组装的内容进行保存到对应文件即可

    3.将以上的docxml文件追加到另一个xml文件中

     XmlDataDocument newdoc = new XmlDataDocument();

                string DirPath = "";

                string outFilePath = "";

                string Data_NO = "";

                string Data_Key = "";

                //生成文件夹及文件内容

                Dictionary<string, string> dictionary = new Dictionary<string, string>();

                Dictionary<string, string> outError = new Dictionary<string, string>();

                var isok = NUtils.CreateFile(doc, "553", out newdoc, out DirPath, out outFilePath, dictionary, out outError, out Data_Key, out Data_NO);

    4.将最新的xml文件打包成zip到指定文件夹下

    ZipHelper.Zip(DirPath, outFilePath, 6);

    说明:ConfigurationManager.AppSettings["IsFile"] 通过配置得是否打包当前文件夹

    ConfigurationManager.AppSettings["DataModel"];//模板路径
    ConfigurationManager.AppSettings["NewFilePath"];//新文件存放路径
    ConfigurationManager.AppSettings["OutFilePath"];//zip输出文件路径
    ConfigurationManager.AppSettings["CodeModel"];//验证文件存放路径
  • 相关阅读:
    python中的 upper() 、lower()、capitalize()、title()方法
    python中的strip()函数的用法
    python中的split()函数的用法
    python中的join()函数的用法
    appium 简单的测试例子(1)
    模拟器连接使用
    appuim连接时的一些出现的错误
    android获取包名的几种方法
    python+Appium(1)
    专注基础软件自研,巨杉入选“2020信创产业独角兽100强”
  • 原文地址:https://www.cnblogs.com/lovable/p/13517370.html
Copyright © 2020-2023  润新知