首页
学习
活动
专区
圈层
工具
发布
首页
学习
活动
专区
圈层
工具
MCP广场
社区首页 >问答首页 >压缩在C#中创建的文件夹

压缩在C#中创建的文件夹
EN

Stack Overflow用户
提问于 2016-01-13 11:17:15
回答 4查看 4.7K关注 0票数 3

我正在C#中创建一个文件夹,希望在创建它之后立即将其压缩。我四处看看(如何压缩文件夹),(http://dotnetzip.codeplex.com/),但到目前为止没有运气。我对使用dotnetzip有点担心,因为它上一次发布是在5年前。

在Visual 2015中,dotnetzip仍然相关吗?还是在不使用包的情况下在C#中有一种更现代的压缩文件夹的方法?

这就是我复制文件夹的方式;

代码语言:javascript
复制
    private static void CopyDirectory(string SourcePath, string DestinationPath, bool overwriteexisting)
    {

        SourcePath = SourcePath.EndsWith(@"\") ? SourcePath : SourcePath + @"\";
        DestinationPath = DestinationPath.EndsWith(@"\") ? DestinationPath : DestinationPath + @"\";

        if (Directory.Exists(SourcePath))
        {
            if (Directory.Exists(DestinationPath) == false)
                Directory.CreateDirectory(DestinationPath);

            foreach (string fls in Directory.GetFiles(SourcePath))
            {
                FileInfo flinfo = new FileInfo(fls);
                flinfo.CopyTo(DestinationPath + flinfo.Name, overwriteexisting);
            }
            foreach (string drs in Directory.GetDirectories(SourcePath))
            {
                DirectoryInfo drinfo = new DirectoryInfo(drs);
                CopyDirectory(drs, DestinationPath + drinfo.Name, overwriteexisting);
            }
        }
    }

我希望在此之后压缩创建的文件夹。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2016-01-13 11:37:22

要压缩文件夹,.Net 4.5框架包含ZipFile.CreateFromDirectory

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

ZipFile.CreateFromDirectory(startPath, zipPath);
票数 7
EN

Stack Overflow用户

发布于 2017-02-07 13:51:28

只是想把我的两分钱加到你已经接受的帖子中作为答案。假设您有一个文件夹结构:

代码语言:javascript
复制
C:\RootFolder
C:\RootFolder\Folder1
C:\RootFolder\Folder1\Folder1a
C:\RootFolder\Folder1\Folder1b
C:\RootFolder\file1.txt
C:\RootFolder\file2.txt

ZipFile.CreateFromDirectory绝对是该走的路。不需要第三次聚会。您只需引用System.IO.Compression.FileSystem

我想指出的是:您可以将整个RootFolder (包括它)压缩到存档中。

代码语言:javascript
复制
ZipFile.CreateFromDirectory(@"C:\RootFolder", @"C:\RootFolder.zip", 
                            CompressionLevel.Optimal, true);

或者没有文件夹本身的RootFolder的内容。

代码语言:javascript
复制
ZipFile.CreateFromDirectory(@"C:\RootFolder", @"C:\RootFolder.zip", 
                            CompressionLevel.Optimal, false);

第四个参数(bool includeBaseDirectory)为我们提供了这个灵活性。希望它能帮到别人。

票数 3
EN

Stack Overflow用户

发布于 2016-01-13 11:26:18

如何在C#中使用不使用第三方API的ZIP文件?涵盖了相同的领域,并为.Net 3.5 (https://stackoverflow.com/a/940621/2381157)和.Net 4.5 (https://stackoverflow.com/a/20200025/2381157)提供了解决方案,因此我感到惊讶的是,@kap没有这样做的.NET类。

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

https://stackoverflow.com/questions/34765258

复制
相关文章

相似问题

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