C#使用SharpZipLib解压Zip单个文件到内存
2016-01-25 17:56
716 查看
DoNetZip也是挺坑的,某些zip解压缩不了,
异常返回“Ionic.Zip.ZipException: Cannot read that as a ZipFile”,
只有和SharpZipLib一起用了。。。
找了半天SharpZipLib的文章,还真没找到解压缩到内存的,难道是搜索引擎问题?
所以自己写了一下
从一个zip里取一个文本文件,我是后面转的文本,可以改为直接使用Stream。
decompressedStream那里使用的是一个MemoryStream,稍微改一下就可以解压到本地磁盘
思路就是循环整个包 找到要解压缩的文件 然后读取返回
异常返回“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 ""; } } } }
相关文章推荐
- Python中zip()函数用法举例
- c#调用COM组件
- zip 的压缩原理与实现
- C#实现把指定数据写入串口
- C#动态创建button的方法
- C#中抽象方法与虚拟方法的区别
- c#中虚函数的相关使用方法
- C#使用加边法计算行列式的值
- C#实现多线程的同步方法实例分析
- C#中尾递归的使用、优化及编译器优化
- C#实现子窗体与父窗体通信方法实例总结
- C#通用邮件发送类分享
- C#中this的用法集锦
- C#数据结构之顺序表(SeqList)实例详解
- C#.NET获取拨号连接的宽带连接方法
- C#异步绑定数据实现方法
- C#实现AddRange为数组添加多个元素的方法
- C#中Equality和Identity浅析
- C#比较二个数组并找出相同或不同元素的方法
- C#生成饼形图及添加文字说明实例代码