Create normal zip file programmatically

后端 未结 11 860
野的像风
野的像风 2020-12-05 00:06

I have seen many tutorials on how to compress a single file in c#. But I need to be able to create a normal *.zip file out of more than just one file. Is there anything in .

相关标签:
11条回答
  • 2020-12-05 00:17

    Here's some code I wrote after using the above posts. Thanks for all your help.

    This code accepts a list of file paths and creates a zip file out of them.

    public class Zip
    {
        private string _filePath;
        public string FilePath { get { return _filePath; } }
    
        /// <summary>
        /// Zips a set of files
        /// </summary>
        /// <param name="filesToZip">A list of filepaths</param>
        /// <param name="sZipFileName">The file name of the new zip (do not include the file extension, nor the full path - just the name)</param>
        /// <param name="deleteExistingZip">Whether you want to delete the existing zip file</param>
        /// <remarks>
        /// Limitation - all files must be in the same location. 
        /// Limitation - must have read/write/edit access to folder where first file is located.
        /// Will throw exception if the zip file already exists and you do not specify deleteExistingZip
        /// </remarks>
        public Zip(List<string> filesToZip, string sZipFileName, bool deleteExistingZip = true)
        {
            if (filesToZip.Count > 0)
            {
                if (File.Exists(filesToZip[0]))
                {
    
                    // Get the first file in the list so we can get the root directory
                    string strRootDirectory = Path.GetDirectoryName(filesToZip[0]);
    
                    // Set up a temporary directory to save the files to (that we will eventually zip up)
                    DirectoryInfo dirTemp = Directory.CreateDirectory(strRootDirectory + "/" + DateTime.Now.ToString("yyyyMMddhhmmss"));
    
                    // Copy all files to the temporary directory
                    foreach (string strFilePath in filesToZip)
                    {
                        if (!File.Exists(strFilePath))
                        {
                            throw new Exception(string.Format("File {0} does not exist", strFilePath));
                        }
                        string strDestinationFilePath = Path.Combine(dirTemp.FullName, Path.GetFileName(strFilePath));
                        File.Copy(strFilePath, strDestinationFilePath);
                    }
    
                    // Create the zip file using the temporary directory
                    if (!sZipFileName.EndsWith(".zip")) { sZipFileName += ".zip"; }
                    string strZipPath = Path.Combine(strRootDirectory, sZipFileName);
                    if (deleteExistingZip == true && File.Exists(strZipPath)) { File.Delete(strZipPath); }
                    ZipFile.CreateFromDirectory(dirTemp.FullName, strZipPath, CompressionLevel.Fastest, false);
    
                    // Delete the temporary directory
                    dirTemp.Delete(true);
    
                    _filePath = strZipPath;                    
                }
                else
                {
                    throw new Exception(string.Format("File {0} does not exist", filesToZip[0]));
                }
            }
            else
            {
                throw new Exception("You must specify at least one file to zip.");
            }
        }
    }
    
    0 讨论(0)
  • 2020-12-05 00:21

    This can be done by adding a reference to System.IO.Compression and System.IO.Compression.Filesystem.

    A sample createZipFile() method may look as following:

    public static void createZipFile(string inputfile, string outputfile, CompressionLevel compressionlevel)
            {
                try
                {
                    using (ZipArchive za = ZipFile.Open(outputfile, ZipArchiveMode.Update))
                    {
                        //using the same file name as entry name
                        za.CreateEntryFromFile(inputfile, inputfile);
                    }
                }
                catch (ArgumentException)
                {
                    Console.WriteLine("Invalid input/output file.");
                    Environment.Exit(-1);
                }
    }
    

    where

    • inputfile= string with the file name to be compressed (for this example, you have to add the extension)
    • outputfile= string with the destination zip file name

    More details about ZipFile Class in MSDN

    0 讨论(0)
  • 2020-12-05 00:23

    This can be done with just one line of code using just Dot Net. Below is sample code copied from MSDN

    Step 1: Add a reference to System.IO.Compression.FileSystem

    Step 2: Follow the code below

            static void Main(string[] args)
            {
                string startPath = @"c:\example\start";
                string zipPath = @"c:\example\result.zip";
                string extractPath = @"c:\example\extract";
    
                ZipFile.CreateFromDirectory(startPath, zipPath);
    
                ZipFile.ExtractToDirectory(zipPath, extractPath);
            }
    
    0 讨论(0)
  • 2020-12-05 00:24

    Here are a few resources you might consider: Creating Zip archives in .NET (without an external library like SharpZipLib)

    Zip Your Streams with System.IO.Packaging

    My recommendation and preference would be to use system.io.packacking. This keeps your dependencies down (just the framework). Jgalloway’s post (the first reference) provides a good example of adding two files to a zip file. Yes, it is more verbose, but you can easily create a façade (to a degree his AddFileToZip does that).

    HTH

    0 讨论(0)
  • 2020-12-05 00:28

    My 2 cents:

        using (ZipArchive archive = ZipFile.Open(zFile, ZipArchiveMode.Create))
        {
            foreach (var fPath in filePaths)
            {
                archive.CreateEntryFromFile(fPath,Path.GetFileName(fPath));
            }
        }
    

    So Zip files could be created directly from files/dirs.

    0 讨论(0)
  • 2020-12-05 00:30

    You can now use the ZipArchive class (System.IO.Compression.ZipArchive), available from .NET 4.5

    You have to add System.IO.Compression as a reference.

    Example: Generating a zip of PDF files

    using (var fileStream = new FileStream(@"C:\temp\temp.zip", FileMode.CreateNew))
    {
        using (var archive = new ZipArchive(fileStream, ZipArchiveMode.Create, true))
        {
            foreach (var creditNumber in creditNumbers)
            {
                var pdfBytes = GeneratePdf(creditNumber);
                var fileName = "credit_" + creditNumber + ".pdf";
                var zipArchiveEntry = archive.CreateEntry(fileName, CompressionLevel.Fastest);
                using (var zipStream = zipArchiveEntry.Open())
                    zipStream.Write(pdfBytes, 0, pdfBytes.Length);
                }
            }
        }
    }
    
    0 讨论(0)
提交回复
热议问题