C# C语言中的Zip文件夹#

C# C语言中的Zip文件夹#,c#,zip,directory,archive,compression,C#,Zip,Directory,Archive,Compression,如何在C#中压缩文件夹的示例(简单代码)是什么 更新: 我没有看到名称空间ICSharpCode。我下载了ICSharpCode.SharpZipLib.dll,但我不知道在哪里复制该dll文件。我需要做什么才能看到这个名称空间 你们有压缩文件夹的MSDN示例的链接吗,因为我读了所有MSDN,但找不到任何东西 好的,但我需要下一个信息 我应该在哪里复制ICSharpCode.SharpZipLib.dll以在Visual Studio中查看该名称空间?BCL中没有任何东西可以为您这样做,但是

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


更新:

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

你们有压缩文件夹的MSDN示例的链接吗,因为我读了所有MSDN,但找不到任何东西


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


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

BCL中没有任何东西可以为您这样做,但是有两个非常好的.NET库确实支持该功能

我已经使用了这两种方法,可以说这两种方法都非常完整,都有设计良好的API,所以这主要是个人喜好的问题


我不确定他们是否明确支持将文件夹而不仅仅是单个文件添加到zip文件中,但是,使用and类创建递归迭代目录及其子目录的内容应该很容易。

上面有一篇文章,其中有一个示例应用程序,用于压缩和解压纯C#格式的文件和文件夹。很长一段时间以来,我一直在成功地使用其中的一些类。如果您需要了解这类情况,代码是在Microsoft许可证下发布的

编辑:感谢奇索指出我有点落后于时代。我提到的MSDN示例实际上正在使用,而且这些天的功能非常全面。根据我以前的经验,我很乐意推荐它

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

Rich

从帮助文件中

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

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


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

以下代码使用第三方:

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

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);
你可以

使用免费的LGPL许可是一种常见的选择


免责声明:我为Rebex工作

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

下面是一个如何使用它的示例。
这个答案随着.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);
可以帮助你完成这项任务。以下代码段压缩文件夹中的文件和目录。你也可以使用威尔卡面具

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();

在.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 (FileStream zipToOpen = new FileStream(@"Test.zip", FileMode.Create))
    {
        using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create))
        {
            foreach (FileInfo file in from.AllFilesAndFolders().Where(o => o is FileInfo).Cast<FileInfo>())
            {
                var relPath = file.FullName.Substring(from.FullName.Length+1);
                ZipArchiveEntry readmeEntry = archive.CreateEntryFromFile(file.FullName, relPath);
            }
        }
    }
}
公共静态类文件扩展
{
公共静态IEnumerable AllFilesAndFolders(此目录信息目录)
{
foreach(dir.GetFiles()中的var f)
收益率f;
foreach(dir.GetDirectories()中的变量d)
{
收益率d;
foreach(所有文件和文件夹中的var o(d))
收益率o;
}
}
}
无效测试()
{
DirectoryInfo from=新的DirectoryInfo(@“C:\Test”);
使用(FileStream zipToOpen=newfilestream(@“Test.zip”,FileMode.Create))
{
使用(ZipArchive archive=new ZipArchive(zipToOpen,ZipArchiveMode.Create))
{
foreach(from.AllFilesAndFolders()中的FileInfo文件,其中(o=>o是FileInfo.Cast())
{
var relPath=file.FullName.Substring(from.FullName.Length+1);
ZipArchiveEntry readmeEntry=archive.CreateEntryFromFile(file.FullName,relPath);
}
}
}
}
文件夹不需要在zip存档中“创建”。CreateEntryFromFile中的第二个参数“entryName”应该是一个相对路径,解包zip文件时,将检测并创建相对路径的目录。

使用DotNetZip(作为nuget软件包提供):

用法:

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

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

MSDN上的示例代码使用DotNetZip,这是一个免费的zip库,支持压缩级别和加密(包括AES加密),尽管您引用的特定示例没有显示这一点。该库生成“正确”的zip文件。感谢您提到这一点。我仍然在使用几年前的原始版本,它只是一个独立的代码示例,所以看起来他们在这方面做了很多工作。我向Cheeso道歉,因为看起来你是管理员,如果不是DotNetZip库的作者的话!事实证明,它对我非常有用,即使是在我第一次遇到它时的早期形式DotNetZip支持通过ZipFile.AddDirectory()方法将目录添加到zip文件中。它在目录中递归。您可以使用SharpZipLib添加文件夹,只需将文件夹名称加上斜杠(无法回忆它是向前还是向后)添加到zip条目名称。SharpZipLib拥有DotNetZip的GPL许可证:+1。我所在的组织广泛使用它,它适合各种任务。(将后续“回答”移到问题中)项目->添加参考->选择library@JohnB这是添加目录的内容。我想包括主目录,就像这里的zip一样,我想要ProhjectX,然后在它的内容中?这很好用。
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");