繁体   English   中英

压缩用C#创建的文件夹

[英]Zip a Folder Created in C#

我正在C#中创建一个文件夹,希望在创建后立即将其压缩。 我环顾了一下( 如何压缩文件夹 ),( http://dotnetzip.codeplex.com/ ),但到目前为止还没有运气。 我有点担心使用dotnetzip,因为它的最新发行是在5年前。

dotnetzip在Visual Studio 2015中是否仍然有用,或者是否有更现代的方式在C#中不使用软件包来压缩文件夹?

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

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

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

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

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

ZipFile.CreateFromDirectory(startPath, zipPath);

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

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压缩到存档中

ZipFile.CreateFromDirectory(@"C:\RootFolder", @"C:\RootFolder.zip", 
                            CompressionLevel.Optimal, true);

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

ZipFile.CreateFromDirectory(@"C:\RootFolder", @"C:\RootFolder.zip", 
                            CompressionLevel.Optimal, false);

第四个参数(bool includeBaseDirectory)为我们提供了这种灵活性 希望它可以帮助某人。

如何不使用任何第三方API在C#中压缩文件? 涵盖了相同的领域,并为.Net 3.5( https://stackoverflow.com/a/940621/2381157 )和.Net 4.5( https://stackoverflow.com/a/20200025/2381157 )提供了解决方案@kap表示没有用于执行此操作的.NET类感到惊讶。

您可以使用第三方dll ICSharpCode.SharpZipLib,在其中可以使用以下加载文件将目录压缩到filsstream fs并继续字节= fs.Read(buffer,0,buffer.Length)zipFile.Write(buffer,0,bytes)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM