(转)Reading zip files from Silverlight

 

Silverlight doesn't have any classes from the System.IO.Compression namespace, but it's gone something better, Application.GetResourceStream.  It's pretty easy to take a stream to a zp file and get a stream to one of the uncomressed files inside it:

 

 

 

StreamResourceInfo zipInfo = new StreamResourceInfo(zipStream, null);
StreamResourceInfo streamInfo = Application.GetResourceStream(zipInfo, new Uri(fileName, UriKind.Relative));
Stream fileStream = streamInfo.Stream;

All you need to do is provide the stream to the zip file, and the name of the file you want to extract, and in three lines of code you have a stream to the uncompressed file.  But there's one snag: What if you don't know the name of the file(s) inside the zip file?  There is no api to browse through the contents of the zip file.  A common workaround is to include a manifest file in the zip which lists the contents of the zip archive, but for some, this isn't possible because they don't conrol the creation of the content, and are just consuming it.  It's actually not too hard to list the files in a zip archive, with a little help from the zip file format specification I wrote a little utility method that lists the files contained in a zip file.  Its usage should be straightforward.

 public class ZipUtil
{

 

 

 

/// <summary>
/// Reads the file names from the header of the zip file
/// </summary>
/// <param name="zipStream">The stream to the zip file</param>
/// <returns>An array of file names stored within the zip file. These file names may also include relative paths.</returns>
public static string[] GetZipContents(System.IO.Stream zipStream)
{

List<string> names = new List<string>();
BinaryReader reader = new BinaryReader(zipStream);
while (reader.ReadUInt32() == 0x04034b50)
{

// Skip the portions of the header we don't care about
reader.BaseStream.Seek(14, SeekOrigin.Current);
uint compressedSize = reader.ReadUInt32();
uint uncompressedSize = reader.ReadUInt32();
int nameLength = reader.ReadUInt16();
int extraLength = reader.ReadUInt16();
byte[] nameBytes = reader.ReadBytes(nameLength);
names.Add(Encoding.UTF8.GetString(nameBytes, 0, nameLength));
reader.BaseStream.Seek(extraLength + compressedSize, SeekOrigin.Current);

}
// Move the stream back to the begining
zipStream.Seek(0, SeekOrigin.Begin);
return names.ToArray();

}

}

 

转载于:https://www.cnblogs.com/allanli/archive/2011/01/07/1929649.html

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

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

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

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值