66 c# compression directory zip archive
如何在C#中压缩文件夹的示例(简单代码)是什么?
更新:
我没有看到命名空间ICSharpCode.我下载ICSharpCode.SharpZipLib.dll但我不知道在哪里复制该DLL文件.要查看此命名空间,我需要做什么?
你有压缩文件夹的MSDN示例的链接,因为我读了所有MSDN但我找不到任何东西.
好的,但我需要下一个信息.
我应该在哪里复制ICSharpCode.SharpZipLib.dll以在Visual Studio中查看该命名空间?
Jar*_*yer 109
这个答案随.NET 4.5而变化.创建一个zip文件变得异常简单.不需要第三方库.
string startPath = @"c:\example\start";
string zipPath = @"c:\example\result.zip";
string extractPath = @"c:\example\extract";
ZipFile.CreateFromDirectory(startPath, zipPath);
ZipFile.ExtractToDirectory(zipPath, extractPath);
Run Code Online (Sandbox Code Playgroud)
Sim*_*mon 49
来自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);
}
Run Code Online (Sandbox Code Playgroud)
Nol*_*rin 21
BCL没有为你做这件事,但有两个很棒的.NET库支持这个功能.
我已经使用了两者,并且可以说这两者非常完整且设计良好的API,所以这主要取决于个人喜好.
我不确定他们是否明确支持添加文件夹而不仅仅是单个文件来压缩文件,但是应该很容易创建一些使用DirectoryInfo和FileInfo类递归迭代目录及其子目录的东西.
Gil*_*tto 10
在.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);
}
}
}
}
Run Code Online (Sandbox Code Playgroud)
文件夹不需要在zip存档中"创建".CreateEntryFromFile中的第二个参数"entryName"应该是一个相对路径,当解压缩zip文件时,将检测并创建相对路径的目录.
System.IO.Packaging命名空间中有一个ZipPackage类,它内置于.NET 3,3.5和4.0中.
http://msdn.microsoft.com/en-us/library/system.io.packaging.zippackage.aspx
以下是如何使用它的示例. http://www.codeproject.com/KB/files/ZipUnZipTool.aspx?display=Print
| 归档时间: |
|
| 查看次数: |
109204 次 |
| 最近记录: |