Click here to Skip to main content
15,922,533 members
Please Sign up or sign in to vote.
1.00/5 (2 votes)
See more:
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
    }
}

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]
Posted
Updated 19-Jul-11 21:04pm
v2
Comments
OriginalGriff 20-Jul-11 3:07am    
Reason for my vote of one: Code dump, no effort.

1 solution

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.
 
Share this answer
 
Comments
vaibhavraidwivedi 20-Jul-11 3:18am    
actually from this code a xml file is creating but i am not able to understand what are its node and attributes . I just want a xml file which created from that..

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900