使用ICSharpCode.dll解压多个压缩文件流

  最近项目中遇到一个技术难点,那就是从ftp上下载压缩的文件流,当然一个压缩文件,往往包含多个文件,那么当拿到一个压缩文件流后,该如何解压呢?

那么此时,一个插件就要派上用场了,那就是ICSharpCode.dll。可以在你的当前程序nuget 中获取这个插件,然后添加引用。

代码如下:

public static string DecompressGzStream(Stream stream)
{
ZipInputStream s = new ZipInputStream(stream);
ZipEntry theEntry;
List<LocationInfo> list = new List<LocationInfo>();
try
{
while ((theEntry = s.GetNextEntry()) != null)
{
string fileName = Path.GetFileNameWithoutExtension(theEntry.Name);
if (fileName != String.Empty)
{
MemoryStream ms = new MemoryStream();
s.CopyTo(ms);
byte[] bytes = ms.ToArray();
string str = System.Text.Encoding.Default.GetString(bytes);
AddTaxiInfor(str, list);
ms.Close();
}

}
s.Close();
}
catch (Exception ex)
{
throw new Exception(ex.Message);
}
System.Web.Script.Serialization.JavaScriptSerializer json = new System.Web.Script.Serialization.JavaScriptSerializer();
string jsonStr = json.Serialize(list);
return jsonStr;
}

 

public static void AddTaxiInfor(string str, List<LocationInfo> list)
{
double d = 0;
string[] arr = str.Split('\n');
for (int i = 0; i < arr.Length - 1; i++)
{
string sigle = arr[i];
string[] little = sigle.Split(',');
LocationInfo entity = new LocationInfo();

if (double.TryParse(little[0], out d) && double.TryParse(little[1], out d))
{
entity.Latitude = Convert.ToDouble(little[0]);
entity.Longitude = Convert.ToDouble(little[1]);
list.Add(entity);
}
}
}

 

不过这个插件也有不足的地方,那就是当循环读取每一个文件的流的时候,如果直接操作当前的文件流,会调用closed(),那么第一次是可以读取的,当第二次循环的时候,就会报空指针异常,不过,我还是用了一个办法给解决了,那就是每获取一个文件流,都重新创建一个流,然后进行复制,然后操作生成的新的流对象,那么就不会再出现这个问题了。好了,就将这么多了。希望能帮到大家。

posted @ 2015-03-30 00:45  梦想的火把永不熄灭  阅读(237)  评论(0编辑  收藏  举报