using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create))
{
using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create))
{
}
}
using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Create))
{
using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Create))
{
System.Reflection.Assembly assemble = System.Reflection.Assembly.GetExecutingAssembly();
string path = assemble.Location;
string filename = System.IO.Path.GetFileName(path);
ZipArchiveEntry readMeEntry = archive.CreateEntry(filename);
using (System.IO.Stream stream = readMeEntry.Open())
{
byte[] bytes = System.IO.File.ReadAllBytes(path);
stream.Write(bytes, 0, bytes.Length);
}
}
}
列出压缩文件内容
当然,也可以通过程序检查压缩文件的内容了。使用 Read 方式就可以了。
using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read))
{
foreach (var zipArchiveEntry in archive.Entries)
Console.WriteLine("FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName);
}
}
提取压缩文件
当然可以从压缩文件中提取被压缩的内容了。
// 读取其中一个文件的内容using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Read))
{
// 解压某个文件
ZipArchiveEntry entry = archive.GetEntry("ZipArchiveSample.exe");
Console.WriteLine(entry.Name);
using (System.IO.Stream stream = entry.Open())
{
System.IO.Stream output = new FileStream("http://www.cnblogs.com/ZipArchiveSample.exe", FileMode.Create);
int b = -1;
while ((b = stream.ReadByte()) != -1)
{
output.WriteByte((byte) b);
}
output.Close();
}
}
}
更新压缩文件
在压缩文件已经创建之后,还可以打开它,继续添加文件,这就称为更新了,使用 Update 模式。
// 向现有的压缩文件中添加文件using (FileStream zipFileToOpen = new FileStream(zipFilePath, FileMode.Open))
{
using (ZipArchive archive = new ZipArchive(zipFileToOpen, ZipArchiveMode.Update))
{
// 这里添加当前正在执行的程序文件本身
System.Reflection.Assembly assemble = System.Reflection.Assembly.GetExecutingAssembly();
string path = assemble.Location;
string filename = System.IO.Path.GetFileName( path);
ZipArchiveEntry readMeEntry = archive.CreateEntry( filename );
using (System.IO.Stream stream = readMeEntry.Open() )
{
byte[] bytes = System.IO.File.ReadAllBytes(path);
stream.Write(bytes, 0, bytes.Length);
}
foreach (var zipArchiveEntry in archive.Entries)
{
Console.WriteLine("FullName of the Zip Archive Entry: {0}", zipArchiveEntry.FullName);
}
}
}