zoukankan      html  css  js  c++  java
  • C# ZIP 压缩解压

    ZIP流是在NetFramework4.5 引入的目的是为了能够更好的操作ZIP文件,进行压缩解压等操作。与ZIP流相关的几个类是:

    1. ZipArchive 代表一个ZIP的压缩包文件
    2. ZipArchiveEntry 代表ZIP压缩包中的一个文件
    3. ZipFile 提供了一系列的静态方法来帮助用户更方便地操作ZIP文件,类似于File类的作用。

    注意:在使用之前请先添加程序集引用System.IO.CompressionSystem.IO.Compression.FileStream

    /// <summary>
    /// 测试
    /// </summary>
    /// <param name="sender"></param>
    /// <param name="e"></param>
    private void BtnZIP_Click(object sender, EventArgs e)
    {
    ZIPYS();
    ZIPJY();
    }

    /// <summary>
    /// 创建压缩zip文档
    /// </summary>
    private void ZIPYS()
    {
    using (FileStream fs = new FileStream("Zip123.zip", FileMode.Create))
    {
    using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Create))
    {
    //创建文档文件
    ZipArchiveEntry entry = zipArchive.CreateEntry("HelloWorld.txt");
    //文档文件写入内容
    using (StreamWriter writer = new StreamWriter(entry.Open(), Encoding.Default))
    {
    writer.Write("I am 鲁迅认识的那只猹! Hello World");
    }
    }
    }
    }

    /// <summary>
    /// 解压zip文档
    /// </summary>
    private void ZIPJY()
    {
    using (FileStream fs = new FileStream("log.zip", FileMode.Open))
    {
    using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
    {
    //创建存放解压文件目录
    Directory.CreateDirectory("log123");
    //解压所有文档文件
    foreach (var it in zipArchive.Entries)
    {
    it.ExtractToFile(@"log123" + it.Name);
    }
    }
    }
    }

    /// <summary>
    /// 向zip文档中添加文档
    /// </summary>
    private void ZIPYStj()
    {
    using (FileStream fs = new FileStream("Zip123.zip", FileMode.Open))
    {
    using (ZipArchive zipArchive = new ZipArchive(fs, ZipArchiveMode.Update))
    {
    ZipArchiveEntry entry = zipArchive.CreateEntry("AppendFile.txt");
    using (StreamWriter wr = new StreamWriter(entry.Open(), Encoding.Default))
    {
    wr.Write("追加内容123!");
    }
    }
    }
    }

    ZipFile

    方法解释
    FileZip.CreateFromDirectory 从一个目录创建ZIP压缩文件
    FileZip.ExtractToDirectory 将ZIP压缩文件解压到目录中
    FileZip.Open 打开一个ZIP压缩文件
    FileZip.OpenRead 打开一个读取模式的ZIP压缩文件

    ZipFileExtensions

    ZipFileExtensions 为ZipArchive 和 ZipArchiveEntry 提供了一些更简便的方法,具体可以查看官方文档

    原文链接:https://www.cnblogs.com/slyfox/p/11231375.html

  • 相关阅读:
    简单读取winfrom资源文件
    string.Format对C#字符串格式化
    如何在SQL中使用循环结构
    Linq to SQL 多条件动态组合查询(实战篇)
    提问的艺术
    XtraGrid 单元格加边框颜色
    凭证控件制作
    C# double 四舍五入
    自定义光标样式
    触发窗体事件(例如按Esc关闭窗体)
  • 原文地址:https://www.cnblogs.com/1175429393wljblog/p/11572726.html
Copyright © 2011-2022 走看看