我使用的是.NET 4.5,如果我尝试使用"CreateFromDirectory"压缩整个目录,ZipFile类的效果很好.但是,我只想在目录中压缩一个文件.我试着指向一个特定的文件(文件夹\ data.txt),但这不起作用.我考虑过ZipArchive类,因为它有一个"CreateEntryFromFile"方法,但似乎这只允许你创建一个现有文件的条目.
有没有办法简单地压缩一个文件而不创建一个空的zipfile(有问题),然后使用ZipArchiveExtension的"CreateEntryFromFile"方法?
**这也是假设我正在开发一个目前无法使用第三方附加组件的公司计划.
示例来自:http://msdn.microsoft.com/en-us/library/ms404280%28v=vs.110%29.aspx
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)
但是如果是startPath @"c:\example\start\myFile.txt;",则会抛出目录无效的错误.
Joh*_*ner 44
使用CreateEntryFromFile关闭存档并使用文件或内存流:
如果您可以创建zip文件然后添加到文件流,请使用文件流:
using (FileStream fs = new FileStream(@"C:\Temp\output.zip",FileMode.Create))
using (ZipArchive arch = new ZipArchive(fs, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}
Run Code Online (Sandbox Code Playgroud)
或者,如果您需要在内存中执行所有操作并在文件完成后写入文件,请使用内存流:
using (MemoryStream ms = new MemoryStream())
using (ZipArchive arch = new ZipArchive(ms, ZipArchiveMode.Create))
{
arch.CreateEntryFromFile(@"C:\Temp\data.xml", "data.xml");
}
Run Code Online (Sandbox Code Playgroud)
然后,您可以将MemoryStream写入文件.
using (FileStream file = new FileStream("file.bin", FileMode.Create, System.IO.FileAccess.Write)) {
byte[] bytes = new byte[ms.Length];
ms.Read(bytes, 0, (int)ms.Length);
file.Write(bytes, 0, bytes.Length);
ms.Close();
}
Run Code Online (Sandbox Code Playgroud)
ziy*_*iya 24
使用文件(或任何)流:
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
{
var entry = zip.CreateEntry("file.txt");
entry.LastWriteTime = DateTimeOffset.Now;
using (var stream= File.OpenRead(@"c:\path\to\file.txt"))
using (var entryStream = entry.Open())
stream.CopyTo(entryStream);
}
Run Code Online (Sandbox Code Playgroud)
或者更简洁:
// reference System.IO.Compression
using (var zip = ZipFile.Open("file.zip", ZipArchiveMode.Create))
zip.CreateEntryFromFile("file.txt", "file.txt");
Run Code Online (Sandbox Code Playgroud)
确保添加对System.IO.Compression的引用
更新
另外,请查看ZipFile和ZipArchive的新dotnet API文档.那里有几个例子.还有关于引用System.IO.Compression.FileSystem使用的警告ZipFile.
要使用ZipFile类,必须在项目中引用System.IO.Compression.FileSystem程序集.
| 归档时间: |
|
| 查看次数: |
35008 次 |
| 最近记录: |