我在C#中创建了一个文件夹,我希望在我创建它之后立即将其压缩。我看了一眼(How to zip a folder),(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);
}
}
}
我希望在此之后压缩创建的文件夹。
答案 0 :(得分:4)
要压缩文件夹,.Net 4.5框架包含ZipFile.CreateFromDirectory:
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
ZipFile.CreateFromDirectory(startPath, zipPath);
答案 1 :(得分:0)
只是想把我的两分钱加到你已经接受的帖子上。 假设你有一个文件夹结构:
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)为我们提供了灵活性。 希望它可以帮到某人。
答案 2 :(得分:-1)
How do I ZIP a file in C#, using no 3rd-party APIs?涵盖了相同的基础,并为.Net 3.5(https://stackoverflow.com/a/940621/2381157)和.Net 4.5(https://stackoverflow.com/a/20200025/2381157)提供了解决方案,所以我很惊讶@kap在那里说这样做不是.NET类。
答案 3 :(得分:-1)
您可以使用第三方dll ICSharpCode.SharpZipLib,您可以使用下面的加载文件将目录压缩到filsstream fs并继续 bytes = fs.Read(buffer,0,buffer.Length)zipFile.Write(buffer,0,bytes)