首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >C#中的Zip文件夹

C#中的Zip文件夹
EN

Stack Overflow用户
提问于 2009-05-25 15:00:35
回答 7查看 139.4K关注 0票数 76

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

更新:

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

你有关于压缩文件夹的MSDN例子的链接吗,因为我读了所有的MSDN,但是我什么也找不到。

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

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

EN

回答 7

Stack Overflow用户

发布于 2012-07-30 22:09:14

此答案在.NET 4.5中有所不同。创建压缩文件becomes incredibly easy。不需要第三方库。

代码语言:javascript
复制
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";

ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
票数 138
EN

Stack Overflow用户

发布于 2009-05-25 07:29:13

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

代码语言:javascript
复制
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);
}
票数 53
EN

Stack Overflow用户

发布于 2016-03-01 01:53:22

在.NET 4.5中,ZipFile.CreateFromDirectory(startPath,zipPath);方法不支持在不将文件和子文件夹放入文件夹的情况下压缩大量文件和子文件夹。当您希望解压缩程序将文件直接放在当前文件夹中时,这是有效的。

这段代码对我来说很有效:

代码语言:javascript
复制
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);
            }
        }
    }
}

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

票数 16
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/905654

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档