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 "";
}
}
}
}