C#使用SharpZipLib解压Zip单个文件到内存

DoNetZip也是挺坑的,某些zip解压缩不了,
异常返回“Ionic.Zip.ZipException: Cannot read that as a ZipFile”,
只有和SharpZipLib一起用了。。。


找了半天SharpZipLib的文章,还真没找到解压缩到内存的,难道是搜索引擎问题?

所以自己写了一下

从一个zip里取一个文本文件,我是后面转的文本,可以改为直接使用Stream。

decompressedStream那里使用的是一个MemoryStream,稍微改一下就可以解压到本地磁盘

思路就是循环整个包 找到要解压缩的文件 然后读取返回

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using ICSharpCode.SharpZipLib;
using ICSharpCode.SharpZipLib.Zip;
using ICSharpCode.SharpZipLib.Checksums;
using System.Diagnostics;

namespace Base
{
    class SharpZip
    {
        public static string UnZipFile(string _zip_file, string _file)
        {
            ZipEntry zipEntry = null;
            try
            {
                using (ZipInputStream zipStream = new ZipInputStream(File.OpenRead(_zip_file)))
                {
                    while ((zipEntry = zipStream.GetNextEntry()) != null)
                    {
                        string fileName = Path.GetFileName(zipEntry.Name);
                        Stream decompressedStream = new MemoryStream();
                        byte[] buffer = new byte[2048];
                        Debug.WriteLine(fileName);
                        if (fileName == _file)
                        {
                            while (true)
                            {
                                int size = zipStream.Read(buffer, 0, buffer.Length);
                                if (size > 0)
                                {
                                    decompressedStream.Write(buffer, 0, size);
                                }
                                else
                                {
                                    break;
                                }
                            }
                            decompressedStream.Position = 0;
                            StreamReader reader = new StreamReader(decompressedStream);
                            string text = reader.ReadToEnd();
                            reader.Close();
                            decompressedStream.Close();
                            return text;
                        }
                    }
                }
                return "";
            }
            catch (System.Exception ex)
            {
                Debug.WriteLine(ex);
                return "";
            }
        }
    }
}
  • 0
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值