在C#中使用XML压缩文件或文件夹 [英] Compressing the file or folder using XML in C#

查看:75
本文介绍了在C#中使用XML压缩文件或文件夹的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

using System;
using System.Linq;
using System.IO;

using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Core;
using System.Collections;
using System.Xml;

namespace Softex.Utilities
{
    public class ZipFile
    {
        private string MySqlConnectionString;
        private ZipOutputStream oZipFileStream;

        public ZipFile(string mySqlConnectionString)
        {
            this.MySqlConnectionString = mySqlConnectionString;
        }
        
        #region " Method to create Zip file"

        /// <summary>
        /// This function will Create the ZIP stream from given xml configuration file
        /// </summary>
        /// <param name="zipConfigXml">Zip XML configuration</param>
        /// <param name="zipStream">MemoryStream to fill the data - ByRef</param>
        public void MakeZipFile(string zipConfigXml, ref MemoryStream zipStream)
        {
            if (zipConfigXml == null) throw new ArgumentNullException("zipConfigXml");

            ZipOutputStream oZipStream = new ZipOutputStream(zipStream);

            // Check if the zip configuration XML is valid XML format or not
            // If it is not a valid XML Request then return the null stream.

            if (Functions.IsValidXmlData(zipConfigXml) == false)
            {
                zipStream = null;
            }
            else
            {
                XmlDocument zipXMLDoc = new XmlDocument();

                // Load the XML Download Confirguration
                zipXMLDoc.LoadXml(zipConfigXml);

                // Select the downloadParts Element to create a file list array
                XmlNodeList nodeListDownloadParts = zipXMLDoc.GetElementsByTagName("downloadParts");

                foreach (XmlNode nodeDownloadParts in nodeListDownloadParts)
                {
                    CreateDownloadPartsFileList(nodeDownloadParts, null, ref oZipStream);
                }

            }

            oZipStream.Finish();
        }
        
        /// <summary>
        /// This function will Create the ZIP stream from given xml configuration file
        /// </summary>
        /// <param name="zipConfigXml">Zip XML configuration</param>
        /// <param name="zipLocation">Location to create a zip file.</param>
        /// <param name="fileName">name of the zip file</param>
        public void MakeZipFile(string zipConfigXml, string zipFilePath)
        {
            if (zipConfigXml == null) throw new ArgumentNullException("zipConfigXml");

            // Check if the zip configuration XML is valid XML format or not
            // If it is not a valid XML Request then return the null stream.
            try
            {
                if (Functions.IsValidXmlData(zipConfigXml))
                {
                    if (!Directory.Exists(Path.GetDirectoryName(zipFilePath)))
                    {
                        Directory.CreateDirectory(Path.GetDirectoryName(zipFilePath));
                    }
                    
                    FileStream fsOutZipFile = File.Create(zipFilePath);
                    oZipFileStream = new ZipOutputStream(fsOutZipFile);

                    XmlDocument zipXMLDoc = new XmlDocument();

                    // Load the XML Download Confirguration
                    zipXMLDoc.LoadXml(zipConfigXml);

                    // Select the downloadParts Element to create a file list array
                    XmlNodeList nodeListDownloadParts = zipXMLDoc.GetElementsByTagName("downloadParts");

                    foreach (XmlNode nodeDownloadParts in nodeListDownloadParts)
                    {
                        AddFilesToZip(nodeDownloadParts, null);
                    }

                    oZipFileStream.IsStreamOwner = true;
                    oZipFileStream.Close();
                }
            }
            catch (Exception ex)
            {
                throw (ex);
            }
            finally
            {
            }
        }

        /// <summary>
        /// This function will Create the Download Parts File List and Add the file into the zip stream
        /// </summary>
        /// <param name="nodeDownloadParts">XmlNode nodeDownloadParts</param>
        /// <param name="aryElementPath">ElementPath Array</param>
        /// <param name="oZipStream">Stream object to fill the data - ByRef</param>
        public void CreateDownloadPartsFileList(XmlNode nodeDownloadParts, ArrayList aryElementPath, ref ZipOutputStream oZipStream)
        {
            XmlNode xnodWorking;
            ArrayList aryWorkingElementPath = new ArrayList();

            bool isSkipTheChildNode = false;

            if (aryElementPath != null)
            {
                foreach (string paths in aryElementPath)
                {
                    aryWorkingElementPath.Add(paths);
                }
            }

            // Sometimes we have designed the child node for file operation. 
            // This will not have any important information regarding the Zip file structure so we can skip
            if (nodeDownloadParts.NodeType == XmlNodeType.Element)
            {
                XmlNamedNodeMap xmlAttributes = nodeDownloadParts.Attributes;
                string fileRelativePath, fileAbsolutePath = null, zipFilePath;

                switch (nodeDownloadParts.Name)
                {
                    case "folder": //Nodename = Folder
                        if (xmlAttributes != null)
                        {
                            if (xmlAttributes.GetNamedItem("isData") != null)
                            {
                                switch (xmlAttributes.GetNamedItem("isData").Value)
                                {
                                    // isData = 0, This folder is just for the representation purpose. This Entry does NOT have any data.
                                    case "0":
                                        aryWorkingElementPath.Add(xmlAttributes.GetNamedItem("id").Value);
                                        break;
                                    // isData = 1, This folder is really a pointer to actual data. This Entry have a location to actual data to copy in the zip file.
                                    case "1":
                                        string folderPath = xmlAttributes.GetNamedItem("path").Value;
                                        if (folderPath != null)
                                        {
                                            if (xmlAttributes.GetNamedItem("isCopyRootFolder") != null)
                                            {
                                                if (xmlAttributes.GetNamedItem("isCopyRootFolder").Value == "1")
                                                {
                                                    aryWorkingElementPath.Add(Path.GetDirectoryName(folderPath));
                                                }
                                            }

                                            ArrayList fileList = GenerateFileList(folderPath);
                                            int trimLength = folderPath.Length;
                                            fileRelativePath = string.Join("\\",
                                                                           (string[])
                                                                           aryWorkingElementPath.ToArray(typeof(string)));
                                            foreach (string fileFullPath in fileList)
                                            {
                                                fileAbsolutePath = fileFullPath;
                                                zipFilePath = fileRelativePath + fileFullPath.Remove(0, trimLength);
                                                WriteToZip(fileAbsolutePath, zipFilePath, ref oZipStream);
                                            }
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        break;
                    case "file": //Nodename = File
                        if (xmlAttributes != null) fileAbsolutePath = xmlAttributes.GetNamedItem("path").Value;
                        fileRelativePath = string.Join("\\", (string[])aryWorkingElementPath.ToArray(typeof(string)));
                        zipFilePath = fileRelativePath + "\\" + Path.GetFileName(fileAbsolutePath);

                        // Check if the file node has childNodes or not
                        // If there is a child node then we need to do some kind of operation with the file so
                        // we need to do opearation and read that file in the buffer and add that buffer to zip file.
                        if (nodeDownloadParts.HasChildNodes)
                        {
                            isSkipTheChildNode = true;
                            MemoryStream zipMemStream = new MemoryStream();
                            //UnicodeEncoding uniEncoding = new UnicodeEncoding();
                            StreamWriter sw = new StreamWriter(zipMemStream) { AutoFlush = true };
                            long count = 0;

                            // Get the NodeList of EditLine from the file node
                            XmlNodeList fileEditLineNodeList = nodeDownloadParts.SelectNodes("editLine");

                            using (StreamReader r = new StreamReader(fileAbsolutePath))
                            {
                                string line;
                                while ((line = r.ReadLine()) != null)
                                {
                                    // Check in the EditLine NodeList if the criteria met replace the string
                                    if (fileEditLineNodeList != null)
                                    {
                                        foreach (XmlNode fileEditLineNode in fileEditLineNodeList)
                                        {
                                            if (fileEditLineNode.Attributes != null)
                                            {
                                                if (line.Contains(fileEditLineNode.Attributes.GetNamedItem("from").Value))
                                                {
                                                    line =
                                                        line.Replace(
                                                            fileEditLineNode.Attributes.GetNamedItem("from").Value,
                                                            fileEditLineNode.Attributes.GetNamedItem("to").Value);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    count++;
                                    sw.WriteLine(line);
                                }
                            }

                            // Get the NodeList of AddLine from the file node
                            XmlNodeList fileAddLineNodeList = nodeDownloadParts.SelectNodes("addLine");
                            if (fileAddLineNodeList != null)
                            {
                                foreach (XmlNode fileAddLineNode in fileAddLineNodeList)
                                {
                                    string newLine = null;
                                    if (fileAddLineNode.Attributes != null)
                                    {
                                        switch (fileAddLineNode.Attributes.GetNamedItem("type").Value)
                                        {
                                            // Depend on the file type if the criteria met replace the string accordingly
                                            case "lstFile":
                                                newLine = ("Reg" + count + fileAddLineNode.InnerText);
                                                break;
                                            default:
                                                newLine = fileAddLineNode.InnerText;
                                                break;
                                        }
                                    }
                                    sw.WriteLine(newLine);
                                    count++;
                                }
                            }

                            byte[] fileBuffer = zipMemStream.ToArray();

                            sw.Close();

                            WriteToZip(fileBuffer, zipFilePath, ref oZipStream);
                        }
                        else
                        {
                            WriteToZip(fileAbsolutePath, zipFilePath, ref oZipStream);
                        }

                        break;
                    ///Nodename = filefromdatabase
                    /// You can fetch the file from database by providing tablename and fileid.

                    case "filefromdatabase":
                        if (xmlAttributes != null)
                        {
                            string tableName = xmlAttributes.GetNamedItem("tablename").Value;
                            string fileName = string.Empty;
                            int fileId = Convert.ToInt32(xmlAttributes.GetNamedItem("fileid").Value);

                            byte[] fileBuffer = Common.Functions.GetFileFromDatabase(this.MySqlConnectionString, tableName, fileId, ref fileName);

                            fileRelativePath = string.Join("\\", (string[])aryWorkingElementPath.ToArray(typeof(string)));
                            zipFilePath = fileRelativePath + "\\" + fileName;

                            WriteToZip(fileBuffer, zipFilePath, ref oZipStream);

                        }
                        break;
                    default:
                        break;
                }
            }

            if ((nodeDownloadParts.HasChildNodes) && !isSkipTheChildNode)
            {
                xnodWorking = nodeDownloadParts.FirstChild;
                while (xnodWorking != null)
                {
                    CreateDownloadPartsFileList(xnodWorking, aryWorkingElementPath, ref oZipStream);
                    xnodWorking = xnodWorking.NextSibling;
                }
            }
        }

        /// <summary>
        /// This function will Create the Download Parts File List and Add the file into the zip stream
        /// </summary>
        /// <param name="nodeDownloadParts">XmlNode nodeDownloadParts</param>
        /// <param name="aryElementPath">ElementPath Array</param>
        /// <param name="oZipStream">Stream object to fill the data - ByRef</param>
        public void AddFilesToZip(XmlNode nodeDownloadParts, ArrayList aryElementPath)
        {
            XmlNode xnodWorking;
            ArrayList aryWorkingElementPath = new ArrayList();

            bool isSkipTheChildNode = false;

            if (aryElementPath != null)
            {
                foreach (string paths in aryElementPath)
                {
                    aryWorkingElementPath.Add(paths);
                }
            }

            // Sometimes we have designed the child node for file operation. 
            // This will not have any important information regarding the Zip file structure so we can skip
            if (nodeDownloadParts.NodeType == XmlNodeType.Element)
            {
                XmlNamedNodeMap xmlAttributes = nodeDownloadParts.Attributes;
                string fileRelativePath, fileAbsolutePath = null, zipFilePath;

                switch (nodeDownloadParts.Name)
                {
                    case "folder": //Nodename = Folder
                        if (xmlAttributes != null)
                        {
                            if (xmlAttributes.GetNamedItem("isData") != null)
                            {
                                switch (xmlAttributes.GetNamedItem("isData").Value)
                                {
                                    // isData = 0, This folder is just for the representation purpose. This Entry does NOT have any data.
                                    case "0":
                                        aryWorkingElementPath.Add(xmlAttributes.GetNamedItem("id").Value);
                                        break;
                                    // isData = 1, This folder is really a pointer to actual data. This Entry have a location to actual data to copy in the zip file.
                                    case "1":
                                        string folderPath = xmlAttributes.GetNamedItem("path").Value;
                                        if (folderPath != null)
                                        {
                                            if (xmlAttributes.GetNamedItem("isCopyRootFolder") != null)
                                            {
                                                if (xmlAttributes.GetNamedItem("isCopyRootFolder").Value == "1")
                                                {
                                                    aryWorkingElementPath.Add(Path.GetDirectoryName(folderPath));
                                                }
                                            }

                                            ArrayList fileList = GenerateFileList(folderPath);
                                            int trimLength = folderPath.Length;
                                            fileRelativePath = string.Join("\\",
                                                                           (string[])
                                                                           aryWorkingElementPath.ToArray(typeof(string)));

                                            foreach (string fileFullPath in fileList)
                                            {
                                                fileAbsolutePath = fileFullPath;
                                                zipFilePath = fileRelativePath + fileFullPath.Remove(0, trimLength);
                                                WriteToZip(fileAbsolutePath, zipFilePath);
                                            }
                                        }
                                        break;
                                    default:
                                        break;
                                }
                            }
                        }
                        break;
                    case "file": //Nodename = File
                        if (xmlAttributes != null) fileAbsolutePath = xmlAttributes.GetNamedItem("path").Value;
                        fileRelativePath = string.Join("\\", (string[])aryWorkingElementPath.ToArray(typeof(string)));
                        zipFilePath = fileRelativePath + "\\" + Path.GetFileName(fileAbsolutePath);

                        // Check if the file node has childNodes or not
                        // If there is a child node then we need to do some kind of operation with the file so
                        // we need to do opearation and read that file in the buffer and add that buffer to zip file.
                        if (nodeDownloadParts.HasChildNodes)
                        {
                            isSkipTheChildNode = true;
                            MemoryStream zipMemStream = new MemoryStream();
                            //UnicodeEncoding uniEncoding = new UnicodeEncoding();
                            StreamWriter sw = new StreamWriter(zipMemStream) { AutoFlush = true };
                            long count = 0;

                            // Get the NodeList of EditLine from the file node
                            XmlNodeList fileEditLineNodeList = nodeDownloadParts.SelectNodes("editLine");

                            using (StreamReader r = new StreamReader(fileAbsolutePath))
                            {
                                string line;
                                while ((line = r.ReadLine()) != null)
                                {
                                    // Check in the EditLine NodeList if the criteria met replace the string
                                    if (fileEditLineNodeList != null)
                                    {
                                        foreach (XmlNode fileEditLineNode in fileEditLineNodeList)
                                        {
                                            if (fileEditLineNode.Attributes != null)
                                            {
                                                if (line.Contains(fileEditLineNode.Attributes.GetNamedItem("from").Value))
                                                {
                                                    line =
                                                        line.Replace(
                                                            fileEditLineNode.Attributes.GetNamedItem("from").Value,
                                                            fileEditLineNode.Attributes.GetNamedItem("to").Value);
                                                    break;
                                                }
                                            }
                                        }
                                    }
                                    count++;
                                    sw.WriteLine(line);
                                }
                            }

                            // Get the NodeList of AddLine from the file node
                            XmlNodeList fileAddLineNodeList = nodeDownloadParts.SelectNodes("addLine");
                            if (fileAddLineNodeList != null)
                            {
                                foreach (XmlNode fileAddLineNode in fileAddLineNodeList)
                                {
                                    string newLine = null;
                                    if (fileAddLineNode.Attributes != null)
                                    {
                                        switch (fileAddLineNode.Attributes.GetNamedItem("type").Value)
                                        {
                                            // Depend on the file type if the criteria met replace the string accordingly
                                            case "lstFile":
                                                newLine = ("Reg" + count + fileAddLineNode.InnerText);
                                                break;
                                            default:
                                                newLine = fileAddLineNode.InnerText;
                                                break;
                                        }
                                    }
                                    sw.WriteLine(newLine);
                                    count++;
                                }
                            }

                            byte[] fileBuffer = zipMemStream.ToArray();

                            sw.Close();

                            WriteToZip(fileBuffer, zipFilePath);
                        }
                        else
                        {
                            WriteToZip(fileAbsolutePath, zipFilePath);
                        }

                        break;
                    ///Nodename = filefromdatabase
                    /// You can fetch the file from database by providing tablename and fileid.

                    case "filefromdatabase":
                        if (xmlAttributes != null)
                        {
                            string tableName = xmlAttributes.GetNamedItem("tablename").Value;
                            string fileName = string.Empty;
                            int fileId = Convert.ToInt32(xmlAttributes.GetNamedItem("fileid").Value);

                            byte[] fileBuffer = Common.Functions.GetFileFromDatabase(this.MySqlConnectionString, tableName, fileId, ref fileName);

                            fileRelativePath = string.Join("\\", (string[])aryWorkingElementPath.ToArray(typeof(string)));
                            zipFilePath = fileRelativePath + "\\" + fileName;

                            WriteToZip(fileBuffer, zipFilePath);

                        }
                        break;
                    default:
                        break;
                }
            }

            if ((nodeDownloadParts.HasChildNodes) && !isSkipTheChildNode)
            {
                xnodWorking = nodeDownloadParts.FirstChild;
                while (xnodWorking != null)
                {
                    AddFilesToZip(xnodWorking, aryWorkingElementPath);
                    xnodWorking = xnodWorking.NextSibling;
                }
            }
        }

        /// <summary>
        /// Read the file by Path and add file binary data into the ZipOutputStream
        /// </summary>
        /// <param name="filePath">File Path </param>
        /// <param name="fileRelativePath">Relative path the file in the zipStream</param>
        /// <param name="oZipStream">provide the ZipOutputStream to add the file entry to it</param>
        public void WriteToZip(string filePath, string fileRelativePath, ref ZipOutputStream oZipStream)
        {
            FileStream oStream;
            byte[] oBuffer = new byte[1024 * 1024];

            ZipEntry oZipEntry = new ZipEntry(fileRelativePath);
            oZipStream.SetLevel(9); // maximum compression
            oZipStream.PutNextEntry(oZipEntry);

            if (!filePath.EndsWith(@"/")) // if a file ends with ''/'' its a directory
            {

                oStream = File.OpenRead(filePath);
                ICSharpCode.SharpZipLib.Core.StreamUtils.Copy(oStream, oZipStream, oBuffer);
                //obuffer = new byte[ostream.Length];
                //ostream.Read(obuffer, 0, obuffer.Length);
                //oZipStream.Write(obuffer, 0, obuffer.Length);
            }
        }

        /// <summary>
        /// Read the file by Path and add file binary data into the ZipOutputStream
        /// </summary>
        /// <param name="filePath">File Path </param>
        /// <param name="fileRelativePath">Relative path the file in the zipStream</param>
        /// <param name="oZipStream">provide the ZipOutputStream to add the file entry to it</param>
        public void WriteToZip(string filePath, string fileRelativePath)
        {
            ZipEntry oZipEntry = new ZipEntry(fileRelativePath);
            oZipFileStream.SetLevel(9); // maximum compression
            oZipFileStream.PutNextEntry(oZipEntry);

            if (!filePath.EndsWith(@"/")) // if a file ends with ''/'' its a directory
            {
                byte[] buffer = new byte[4096];
                using (FileStream oStream = File.OpenRead(filePath))
                {
                    StreamUtils.Copy(oStream, oZipFileStream, buffer);
                }
                oZipFileStream.CloseEntry();
            }
        }

        /// <summary>
        /// Add the file binary data into the ZipOutputStream
        /// </summary>
        /// <param name="fileBuffer">File buffer</param>
        /// <param name="fileRelativePath">Relative path the file in the zipStream</param>
        /// <param name="oZipStream">provide the ZipOutputStream to add the file entry to it</param>
        public void WriteToZip(byte[] fileBuffer, string fileRelativePath, ref ZipOutputStream oZipStream)
        {
            ZipEntry oZipEntry = new ZipEntry(fileRelativePath);
            oZipStream.SetLevel(9); // maximum compression
            oZipStream.PutNextEntry(oZipEntry);

            oZipStream.Write(fileBuffer, 0, fileBuffer.Length);
        }

        /// <summary>
        /// Add the file binary data into the ZipOutputStream
        /// </summary>
        /// <param name="fileBuffer">File buffer</param>
        /// <param name="fileRelativePath">Relative path the file in the zipStream</param>
        /// <param name="oZipStream">provide the ZipOutputStream to add the file entry to it</param>
        public void WriteToZip(byte[] fileBuffer, string fileRelativePath)
        {
            ZipEntry oZipEntry = new ZipEntry(fileRelativePath);
            oZipFileStream.SetLevel(9); // maximum compression
            oZipFileStream.PutNextEntry(oZipEntry);

            oZipFileStream.Write(fileBuffer, 0, fileBuffer.Length);
            oZipFileStream.CloseEntry();
        }

        /// <summary>
        /// This Function will create ArrayList of all the files & folder path of given directory
        /// </summary>
        /// <param name="Dir">Directory Path to create ArrayList</param>
        /// <returns>ArrayList of path for the all subfolders and files</returns>
        public ArrayList GenerateFileList(string Dir)
        {
            ArrayList fils = new ArrayList();

            bool Empty = true;

            if (Directory.Exists(Dir))
            {
                foreach (string file in Directory.GetFiles(Dir)) // add each file in directory
                {
                    fils.Add(file);
                    Empty = false;
                }

                if (Empty)
                {
                    if (Directory.GetDirectories(Dir).Length == 0)
                    {
                        fils.Add(Dir + @"/");
                    }
                }

                foreach (string dirs in Directory.GetDirectories(Dir)) // recursive
                {
                    foreach (object obj in GenerateFileList(dirs))
                    {
                        fils.Add(obj);
                    }
                }
            }

            return fils; // return file list
        }

        #endregion
    }
}


它是一种压缩文件的实用程序.我想使用这个工具.为此,我必须从中创建一个XML文件,然后在进行下载时使用它.谁能建议我通过此代码输出的XML文件是什么.


[edit]添加了代码块-至少我们可以将其折叠...-OriginalGriff [/edit]


Its a utility which compress the file . I want to use this utility . For that i have to create a XML file from it and then use it when download occurs . Will anyone suggest me what is the XML file output through this code.


[edit]Code block added - so at least we can collapse it... - OriginalGriff[/edit]

推荐答案

这是一个代码转储.您没有尝试过帮助自己,也没有尝试过帮助我们-您只是从某个地方拿起了一个文件,并将其转储到一个问题"中.

您的问题"似乎是这是做什么的?"

答案是:查看从哪里获得代码.如有必要,请问他们.

将来只发布相关的代码片段.
That is a code dump. You have made no attempt to help yourself, or us - you have just picked up a file from somewhere, and dumped it into a "question".

Your "question" appear to be "what does this do?"

The answer is: Look at where you got the code from. Ask them if necessary.

And in future, post only relevant code fragments.


这篇关于在C#中使用XML压缩文件或文件夹的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆