在C#中如何压缩文件夹的示例(简单代码)是什么?
更新:
我没有看到命名空间ICSharpCode
。我下载了ICSharpCode.SharpZipLib.dll
,但我不知道将该DLL文件复制到哪里。我需要做什么才能看到这个命名空间?
你有关于压缩文件夹的MSDN例子的链接吗,因为我读了所有的MSDN,但是我什么也找不到。
好的,但我需要下一步的信息。
我应该将ICSharpCode.SharpZipLib.dll
复制到哪里才能在Visual Studio中查看该命名空间?
发布于 2012-07-30 22:09:14
此答案在.NET 4.5中有所不同。创建压缩文件becomes incredibly easy。不需要第三方库。
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
发布于 2009-05-25 07:29:13
在DotNetZip帮助文件中,http://dotnetzip.codeplex.com/releases/
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);
}
发布于 2016-03-01 01:53:22
在.NET 4.5中,ZipFile.CreateFromDirectory(startPath,zipPath);方法不支持在不将文件和子文件夹放入文件夹的情况下压缩大量文件和子文件夹。当您希望解压缩程序将文件直接放在当前文件夹中时,这是有效的。
这段代码对我来说很有效:
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“应该是一个相对路径,在解压压缩文件时,将检测并创建相对路径的目录。
https://stackoverflow.com/questions/905654
复制相似问题