C# 中的 Zip 文件夹

发布于 2024-07-22 16:32:55 字数 346 浏览 3 评论 0 原文

如何在 C# 中压缩文件夹的示例(简单代码)是什么?


更新:

我没有看到命名空间 ICSharpCode。 我下载了 ICSharpCode.SharpZipLib.dll,但我不知道在哪里复制该 DLL 文件。 我需要做什么才能看到这个命名空间?

您是否有压缩文件夹的 MSDN 示例的链接,因为我阅读了所有 MSDN,但找不到任何内容。


好的,但我需要下一个信息。

我应该在哪里复制 ICSharpCode.SharpZipLib.dll 才能在 Visual Studio 中查看该命名空间?

What is an example (simple code) of how to zip a folder in C#?


Update:

I do not see namespace ICSharpCode. I downloaded ICSharpCode.SharpZipLib.dll but I do not know where to copy that DLL file. What do I need to do to see this namespace?

And do you have link for that MSDN example for compress folder, because I read all MSDN but I couldn't find anything.


OK, but I need next information.

Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(10

故人爱我别走 2024-07-29 16:32:55

这个答案随着 .NET 4.5 的改变而改变。 创建 zip 文件 变为非常简单。 不需要第三方库。

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);

This answer changes with .NET 4.5. Creating a zip file becomes incredibly easy. No third-party libraries will be required.

string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
满身野味 2024-07-29 16:32:55

DotNetZip 帮助文件中,http://dotnetzip.codeplex.com/releases/

using (ZipFile zip = new ZipFile())
{
   zip.UseUnicodeAsNecessary= true;  // utf-8
   zip.AddDirectory(@"MyDocuments\ProjectX");
   zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
   zip.Save(pathToSaveZipFile);
}

From the DotNetZip help file, http://dotnetzip.codeplex.com/releases/

using (ZipFile zip = new ZipFile())
{
   zip.UseUnicodeAsNecessary= true;  // utf-8
   zip.AddDirectory(@"MyDocuments\ProjectX");
   zip.Comment = "This zip was created at " + System.DateTime.Now.ToString("G") ; 
   zip.Save(pathToSaveZipFile);
}
风流物 2024-07-29 16:32:55

BCL 中没有任何内容可以为您执行此操作,但有两个出色的 .NET 库确实支持该功能。

两者我都用过,可以说两者都非常完善,并且有设计良好的 API,所以主要看个人喜好了。

我不确定他们是否明确支持添加文件夹而不仅仅是将单个文件添加到zip文件中,但是使用<创建在目录及其子目录上递归迭代的东西应该很容易a href="http://msdn.microsoft.com/en-us/library/system.io.directoryinfo.aspx" rel="noreferrer">DirectoryInfoFileInfo 类。

There's nothing in the BCL to do this for you, but there are two great libraries for .NET which do support the functionality.

I've used both and can say that the two are very complete and have well-designed APIs, so it's mainly a matter of personal preference.

I'm not sure whether they explicitly support adding Folders rather than just individual files to zip files, but it should be quite easy to create something that recursively iterated over a directory and its sub-directories using the DirectoryInfo and FileInfo classes.

ま柒月 2024-07-29 16:32:55

在 .NET 4.5 中,ZipFile.CreateFromDirectory(startPath, zipPath); 该方法不包括您希望压缩多个文件和子文件夹而不必将它们放在文件夹中的情况。 当您希望解压缩将文件直接放入当前文件夹中时,此选项有效。

这段代码对我有用:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (var zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (var file in from.AllFilesAndFolders().OfType<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

不需要在 zip 存档中“创建”文件夹。 CreateEntryFromFile 中的第二个参数“entryName”应该是相对路径,当解压 zip 文件时,将检测并创建相对路径的目录。

In .NET 4.5 the ZipFile.CreateFromDirectory(startPath, zipPath); method does not cover a scenario where you wish to zip a number of files and sub-folders without having to put them within a folder. This is valid when you wish the unzip to put the files directly within the current folder.

This code worked for me:

public static class FileExtensions
{
    public static IEnumerable<FileSystemInfo> AllFilesAndFolders(this DirectoryInfo dir)
    {
        foreach (var f in dir.GetFiles())
            yield return f;
        foreach (var d in dir.GetDirectories())
        {
            yield return d;
            foreach (var o in AllFilesAndFolders(d))
                yield return o;
        }
    }
}

void Test()
{
    DirectoryInfo from = new DirectoryInfo(@"C:\Test");
    using (var zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (var archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (var file in from.AllFilesAndFolders().OfType<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}

Folders don't need to be "created" in the zip-archive. The second parameter "entryName" in CreateEntryFromFile should be a relative path, and when unpacking the zip-file the directories of the relative paths will be detected and created.

七堇年 2024-07-29 16:32:55

System.IO.Packaging 命名空间中有一个 ZipPackage 类,它内置于 .NET 3、3.5 和 4.0 中。

http://msdn.microsoft.com/en-us /library/system.io.packaging.zippackage.aspx

下面是如何使用它的示例。
http://www.codeproject.com/KB/files/ZipUnZipTool.aspx ?显示=打印

There is a ZipPackage class in the System.IO.Packaging namespace which is built into .NET 3, 3.5, and 4.0.

http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx

Here is an example how to use it.
http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print

樱花细雨 2024-07-29 16:32:55

MSDN 上有一篇文章 有一个示例应用程序,用于纯粹用 C# 压缩和解压缩文件和文件夹。 我已经成功使用其中的一些课程很长时间了。 如果您需要了解此类信息,该代码是根据 Microsoft 许可许可证发布的。

编辑:感谢 Cheeso 指出我有点落后于时代。 我指出的 MSDN 示例实际上是使用 DotNetZip 并且现在功能确实非常齐全。 根据我之前版本的经验,我很乐意推荐它。

SharpZipLib 也是一个相当成熟的库,受到人们的高度评价,可以在GPL 许可证。 这实际上取决于您的压缩需求以及您如何查看每个压缩的许可条款。

富有的

There's an article over on MSDN that has a sample application for zipping and unzipping files and folders purely in C#. I've been using some of the classes in that successfully for a long time. The code is released under the Microsoft Permissive License, if you need to know that sort of thing.

EDIT: Thanks to Cheeso for pointing out that I'm a bit behind the times. The MSDN example I pointed to is in fact using DotNetZip and is really very fully-featured these days. Based on my experience of a previous version of this I'd happily recommend it.

SharpZipLib is also quite a mature library and is highly rated by people, and is available under the GPL license. It really depends on your zipping needs and how you view the license terms for each of them.

Rich

幻想少年梦 2024-07-29 16:32:55

使用 DotNetZip(以 nuget 包形式提供):

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

用法:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

或者

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");

using DotNetZip (available as nuget package):

public void Zip(string source, string destination)
{
    using (ZipFile zip = new ZipFile
    {
        CompressionLevel = CompressionLevel.BestCompression
    })
    {
        var files = Directory.GetFiles(source, "*",
            SearchOption.AllDirectories).
            Where(f => Path.GetExtension(f).
                ToLowerInvariant() != ".zip").ToArray();

        foreach (var f in files)
        {
            zip.AddFile(f, GetCleanFolderName(source, f));
        }

        var destinationFilename = destination;

        if (Directory.Exists(destination) && !destination.EndsWith(".zip"))
        {
            destinationFilename += $"\\{new DirectoryInfo(source).Name}-{DateTime.Now:yyyy-MM-dd-HH-mm-ss-ffffff}.zip";
        }

        zip.Save(destinationFilename);
    }
}

private string GetCleanFolderName(string source, string filepath)
{
    if (string.IsNullOrWhiteSpace(filepath))
    {
        return string.Empty;
    }

    var result = filepath.Substring(source.Length);

    if (result.StartsWith("\\"))
    {
        result = result.Substring(1);
    }

    result = result.Substring(0, result.Length - new FileInfo(filepath).Name.Length);

    return result;
}

Usage:

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest");

Or

Zip(@"c:\somefolder\subfolder\source", @"c:\somefolder2\subfolder2\dest\output.zip");
初见终念 2024-07-29 16:32:55

以下代码使用第三方 来自 Rebex 的 ZIP 组件

// add content of the local directory C:\Data\  
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist) 
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");

或者如果您想添加更多文件夹,无需多次打开和关闭存档:

using Rebex.IO.Compression;
...

// open the ZIP archive from an existing file 
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);

// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");

// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");

// close the archive 
zip.Close(ArchiveSaveAction.Auto);

您可以在此处下载 ZIP 组件

使用免费的 LGPL 许可的 SharpZipLib 是一种常见的替代方案。

免责声明:我为 Rebex 工作

Following code uses a third-party ZIP component from Rebex:

// add content of the local directory C:\Data\  
// to the root directory in the ZIP archive
// (ZIP archive C:\archive.zip doesn't have to exist) 
Rebex.IO.Compression.ZipArchive.Add(@"C:\archive.zip", @"C:\Data\*", "");

Or if you want to add more folders without need to open and close archive multiple times:

using Rebex.IO.Compression;
...

// open the ZIP archive from an existing file 
ZipArchive zip = new ZipArchive(@"C:\archive.zip", ArchiveOpenMode.OpenOrCreate);

// add first folder
zip.Add(@"c:\first\folder\*","\first\folder");

// add second folder
zip.Add(@"c:\second\folder\*","\second\folder");

// close the archive 
zip.Close(ArchiveSaveAction.Auto);

You can download the ZIP component here.

Using a free, LGPL licensed SharpZipLib is a common alternative.

Disclaimer: I work for Rebex

方圜几里 2024-07-29 16:32:55

“我应该在哪里复制 ICSharpCode.SharpZipLib.dll 才能在 Visual Studio 中查看该命名空间?”

您需要将 dll 文件添加为项目中的引用。 右键单击“解决方案资源管理器”中的“引用”->“添加引用”->“浏览”,然后选择 dll。

最后,您需要将其作为 using 语句添加到您想要使用它的任何文件中。

"Where should I copy ICSharpCode.SharpZipLib.dll to see that namespace in Visual Studio?"

You need to add the dll file as a reference in your project. Right click on References in the Solution Explorer->Add Reference->Browse and then select the dll.

Finally you'll need to add it as a using statement in whatever files you want to use it in.

毁梦 2024-07-29 16:32:55

ComponentPro ZIP 可以帮助您完成该任务。 以下代码片段将文件和目录压缩到文件夹中。 您也可以使用通配符掩码。

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip 有更多示例

ComponentPro ZIP can help you achieve that task. The following code snippet compress files and dirs in a folder. You can use wilcard mask as well.

using ComponentPro.Compression;
using ComponentPro.IO;

...

// Create a new instance.
Zip zip = new Zip();
// Create a new zip file.
zip.Create("test.zip");

zip.Add(@"D:\Temp\Abc"); // Add entire D:\Temp\Abc folder to the archive.

// Add all files and subdirectories from 'c:\test' to the archive.
zip.AddFiles(@"c:\test");
// Add all files and subdirectories from 'c:\my folder' to the archive.
zip.AddFiles(@"c:\my folder", "");
// Add all files and subdirectories from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22");
// Add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2", "22", "*.dat");
// Or simply use this to add all .dat files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat", "22");
// Add *.dat and *.exe files from 'c:\my folder' to '22' folder within the archive.
zip.AddFiles(@"c:\my folder2\*.dat;*.exe", "22");

TransferOptions opt = new TransferOptions();
// Donot add empty directories.
opt.CreateEmptyDirectories = false;
zip.AddFiles(@"c:\abc", "/", opt);

// Close the zip file.
zip.Close();

http://www.componentpro.com/doc/zip has more examples

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文