How can I Compress a directory with .NET?

前端 未结 10 2681
孤街浪徒
孤街浪徒 2021-02-14 16:16

I have a directory that contains several files. I want compress this folder to a zip or tar.gz file. How can I do his work in C#?

10条回答
  •  清酒与你
    2021-02-14 16:26

    You can zip the directory in pure .NET 3.0.

    First, you will need a reference to WindowsBase.dll.

    This code will open or create a zip file, create a directory inside, and place the file in that directory. If you want to zip a folder, possibly containing sub-directories, you could loop through the files in the directory and call this method for each file. Then, you could depth-first search the sub-directories for files, call the method for each of those and pass in the path to create that hierarchy within the zip file.

    public void AddFileToZip(string zipFilename, string fileToAdd, string destDir)
    {
        using (Package zip = System.IO.Packaging.Package.Open(zipFilename, FileMode.OpenOrCreate))
        {
            string destFilename = "." + destDir + "\\" + Path.GetFileName(fileToAdd);
            Uri uri = PackUriHelper.CreatePartUri(new Uri(destFilename, UriKind.Relative));
            if (zip.PartExists(uri))
            {
                zip.DeletePart(uri);
            }
            PackagePart part = zip.CreatePart(uri, "", CompressionOption.Normal);
    
            using (FileStream fileStream = new FileStream(fileToAdd, FileMode.Open, FileAccess.Read))
            {
                using (Stream dest = part.GetStream())
                {
                    CopyStream(fileStream, dest);
                }
            }
        }
    }
    

    destDir could be an empty string, which would place the file directly in the zip.

    Sources: https://weblogs.asp.net/jongalloway/creating-zip-archives-in-net-without-an-external-library-like-sharpziplib

    https://weblogs.asp.net/albertpascual/creating-a-folder-inside-the-zip-file-with-system-io-packaging

提交回复
热议问题