c USES the DotNetZip encapsulation class to manipulate the zip file of to create and to read the and update instance

  • 2020-05-26 09:58:44
  • OfStack

Download address here: http: / / dotnetzip codeplex. com /

There are many dll files in the downloaded package. You can refer to Ionic.Zip.dll as follows:

Then reference the namespace:

using Ionic.Zip;

Here is one of the classes I encapsulated myself:


/// <summary>
    /// Zip Based on the operation  DotNetZip  The encapsulation 
    /// </summary>
    public static class ZipUtils
    {
        /// <summary>
        ///  Gets the specified input stream ZIP Compressed stream object [original stream object will not change] 
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <returns></returns>
        public static Stream ZipCompress(Stream sourceStream, string entryName = "zip")
        {
            MemoryStream compressedStream = new MemoryStream();
            if (sourceStream != null)
            {
                long sourceOldPosition = 0;
                try
                {
                    sourceOldPosition = sourceStream.Position;
                    sourceStream.Position = 0;
                    using (ZipFile zip = new ZipFile())
                    {
                        zip.AddEntry(entryName, sourceStream);
                        zip.Save(compressedStream);
                        compressedStream.Position = 0;
                    }
                }
                catch
                {
                }
                finally
                {
                    try
                    {
                        sourceStream.Position = sourceOldPosition;
                    }
                    catch
                    {
                    }
                }
            }
            return compressedStream;
        }

        /// <summary>
        ///  Gets the specified array of bytes ZIP Extract the stream object 
        ///  The current method applies only to only 1 The compressed package of a compressed file, that is, the method only takes the first in the compressed package 1 File compression 
        /// </summary>
        /// <param name="sourceStream"></param>
        /// <returns></returns>
        public static Stream ZipDecompress(byte[] data)
        {
            Stream decompressedStream = new MemoryStream();
            if (data != null)
            {
                try
                {
                    MemoryStream dataStream = new MemoryStream(data);
                    using (ZipFile zip = ZipFile.Read(dataStream))
                    {
                        if (zip.Entries.Count > 0)
                        {
                            zip.Entries.First().Extract(decompressedStream);
                            // Extract The method will operate ms , the following must be used first Stream The position is reset to zero, otherwise no data will be read later 
                            //  Returns the Stream Before the object 1 Second position zero action 
                            decompressedStream.Position = 0;
                        }
                    }
                }
                catch
                {
                }
            }
            return decompressedStream;
        }
        /// <summary>
        ///  The compression ZIP file 
        ///  Support for multiple files and directories, or multiple files and directories 1 The compression 
        /// </summary>
        /// <param name="list"> A collection of files or directories to compress </param>
        /// <param name="strZipName"> Compressed file name </param>
        /// <param name="IsDirStruct"> Whether to compress by directory structure </param>
        /// <returns> Success: true/ Failure: false</returns>
        public static bool CompressMulti(List<string> list, string strZipName, bool IsDirStruct)
        {
            try
            {
                using (ZipFile zip = new ZipFile(Encoding.Default))// Set the encoding, when the compression file to solve the Chinese garbled code 
                {
                    foreach (string path in list)
                    {
                        string fileName = Path.GetFileName(path);// Take directory name 
                        // If it's a directory 
                        if (Directory.Exists(path))
                        {
                            if (IsDirStruct)// Compress by directory structure 
                            {
                                zip.AddDirectory(path, fileName);
                            }
                            else// The files in the directory are all compressed to Zip The root directory of the 
                            {
                                zip.AddDirectory(path);
                            }
                        }
                        if (File.Exists(path))// If it's a file 
                        {
                            zip.AddFile(path);
                        }
                    }
                    zip.Save(strZipName);// The compression 
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }
        /// <summary>
        ///  Unpack the ZIP file 
        /// </summary>
        /// <param name="strZipPath"> To extract the ZIP file </param>
        /// <param name="strUnZipPath"> Extract the directory </param>
        /// <param name="overWrite"> Whether or not covered </param>
        /// <returns> Success: true/ Failure: false</returns>
        public static bool Decompression(string strZipPath, string strUnZipPath, bool overWrite)
        {
            try
            {
                ReadOptions options = new ReadOptions();
                options.Encoding = Encoding.Default;// Set the code to resolve the unzip file Chinese garbled code 
                using (ZipFile zip = ZipFile.Read(strZipPath, options))
                {
                    foreach (ZipEntry entry in zip)
                    {
                        if (string.IsNullOrEmpty(strUnZipPath))
                        {
                            strUnZipPath = strZipPath.Split('.').First();
                        }
                        if (overWrite)
                        {
                            entry.Extract(strUnZipPath, ExtractExistingFileAction.OverwriteSilently);// Unzip the file and override it if it already exists 
                        }
                        else
                        {
                            entry.Extract(strUnZipPath, ExtractExistingFileAction.DoNotOverwrite);// Unzip the file if it already exists without overwriting it 
                        }
                    }
                    return true;
                }
            }
            catch (Exception)
            {
                return false;
            }
        }

    }

Usage:

1. Compress files


List<string> list = new List<string>();
  list.Add(@"D:\Test\ss");
  list.Add(@"D:\Test\test1.jpg");
  list.Add(@"D:\ Company documents .txt");
  list.Add(@"D:\Test\ss.xml"); 
  bool isSuc =ZipUtils. CompressMulti(list, "D:\\Test2.zip",true);

2. Unzip the file


bool isSuc = ZipUtils.Decompression("D:\\Test\\Test1.zip", "D:\\Teest", true); 


Related articles: