How to zip multiple files using only .net api in c#

前端 未结 9 1324
灰色年华
灰色年华 2020-12-01 09:04

I like to zip multiple files which are being created dynamically in my web application. Those files should be zipped. For this, i dont want to use any third-party tools. jus

9条回答
  •  臣服心动
    2020-12-01 09:59

    With the release of the .NET Framework 4.5 this is actually a lot easier now with the updates to System.IO.Compression which adds the ZipFile class. There is a good walk-through on codeguru; however, the basics are in line with the following example:

    using System.Collections.Generic;
    using System.IO;
    using System.IO.Compression;
    using System.IO.Compression.FileSystem;
    
    namespace ZipFileCreator
    {
        public static class ZipFileCreator
        {
            /// 
            /// Create a ZIP file of the files provided.
            /// 
            /// The full path and name to store the ZIP file at.
            /// The list of files to be added.
            public static void CreateZipFile(string fileName, IEnumerable files)
            {
                // Create and open a new ZIP file
                var zip = ZipFile.Open(fileName, ZipArchiveMode.Create);
                foreach (var file in files)
                {
                    // Add the entry for each file
                    zip.CreateEntryFromFile(file, Path.GetFileName(file), CompressionLevel.Optimal);
                }
                // Dispose of the object when we are done
                zip.Dispose();
            }
        }
    }
    

提交回复
热议问题