我正在C#中创建一个文件夹,希望在创建它之后立即将其压缩。我四处看看(如何压缩文件夹),(http://dotnetzip.codeplex.com/),但到目前为止没有运气。我对使用dotnetzip有点担心,因为它上一次发布是在5年前。
在Visual 2015中,dotnetzip仍然相关吗?还是在不使用包的情况下在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);
}
}
}我希望在此之后压缩创建的文件夹。
发布于 2016-01-13 11:37:22
要压缩文件夹,.Net 4.5框架包含ZipFile.CreateFromDirectory
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath);发布于 2017-02-07 13:51:28
只是想把我的两分钱加到你已经接受的帖子中作为答案。假设您有一个文件夹结构:
C:\RootFolder
C:\RootFolder\Folder1
C:\RootFolder\Folder1\Folder1a
C:\RootFolder\Folder1\Folder1b
C:\RootFolder\file1.txt
C:\RootFolder\file2.txtZipFile.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)为我们提供了这个灵活性。希望它能帮到别人。
发布于 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类。
https://stackoverflow.com/questions/34765258
复制相似问题