How to compress files

2019-03-09 16:10发布

I want to compress a file and a directory in C#. I found some solution in Internet but they are so complex and I couldn't run them in my project. Can anybody suggest me a clear and effective solution?

10条回答
走好不送
2楼-- · 2019-03-09 16:43

I'm adding this answer as I've found an easier way than any of the existing answers:

  1. Install DotNetZip DLLs in your solution (easiest way is to install the package from nuget)
  2. Add a reference to the DLL.
  3. Import the namespace by adding: using Ionic.Zip;
  4. Zip your file

Code:

using (ZipFile zip = new ZipFile())
{
    zip.AddFile("C:\test\test.txt");
    zip.AddFile("C:\test\test2.txt");
    zip.Save("C:\output.zip");
}

If you don't want the original folder structure mirrored in the zip file, then look at the overrides for AddFile() and AddFolder() etc.

查看更多
唯我独甜
3楼-- · 2019-03-09 16:44

Using DotNetZip http://dotnetzip.codeplex.com/, there's an AddDirectory() method on the ZipFile class that does what you want:

using (var zip = new Ionic.Zip.ZipFile())
{
    zip.AddDirectory("DirectoryOnDisk", "rootInZipFile");
    zip.Save("MyFile.zip");
}

Bonne continuation...

查看更多
等我变得足够好
4楼-- · 2019-03-09 16:45

There is a built-in class in System.IO.Packaging called the ZipPackage:

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage(v=vs.100).aspx

查看更多
SAY GOODBYE
5楼-- · 2019-03-09 16:45

Use http://dotnetzip.codeplex.com/ to ZIP files or directory, there is no builtin class to do it directly in .NET

查看更多
叛逆
7楼-- · 2019-03-09 16:52

For .Net Framework 4.5 this is the most clear example I found:

using System;
using System.IO;
using System.IO.Compression;

namespace ConsoleApplication
{
    class Program
    {
        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);
        }
    }
}

You'll need to add a reference to System.IO.Compression.FileSystem

From: https://docs.microsoft.com/en-us/dotnet/standard/io/how-to-compress-and-extract-files

查看更多
登录 后发表回答