ZipArchive For Windows 8 Apps

工作需求,整理:

ZipHelper.cs
 1     /// <summary>
 2     /// Compression & decompression for a single file.
 3     /// </summary>
 4     public static class ZipHelper
 5     {
 6         /// <summary>
 7         /// Compress a single file to a zipFile.
 8         /// </summary>
 9         /// <param name="srcFileName">the name of the specified source file</param>
10         /// <param name="srcFilePath">the path of the specified source file</param>
11         /// <param name="zipFilePath">the path of the specified zip file</param>
12         public static void Compressing(string srcFileName,string srcFilePath, string zipFilePath)
13         {
14             var zipStream = FileHelper.OpenFile(zipFilePath).Result.OpenStreamForWriteAsync().Result;
15             var srcFile = FileHelper.OpenFile(srcFilePath).Result;
16             var streams = srcFile.OpenStreamForReadAsync().Result;
17             var buffers =new byte[streams.Length];
18             streams.Read(buffers, 0, buffers.Length);
19             using (zipStream)
20             {
21                 using (var zipArchive = new ZipArchive(zipStream, ZipArchiveMode.Create))
22                 {
23                     var entry = zipArchive.CreateEntry(srcFileName);
24                     using (var stream=entry.Open())
25                     {
26                         var bytes = buffers;
27                         stream.Write(bytes,0,bytes.Length);
28                     }
29                 } 
30             }
31         }
32 
33 
34         /// <summary>
35         /// 解压单个文件
36         /// </summary>
37         /// <param name="zipFilePath">压缩文件路径</param>
38         /// <param name="desFilePath">存放文件路径</param>
39         public  static  void Decompressing(string zipFilePath,string desFilePath)
40         {
41             var zipStream = FileHelper.OpenFileStream(zipFilePath, FileAccessMode.ReadWrite).Result.AsStream();
42             var desFileStream = FileHelper.OpenFileStream(desFilePath, FileAccessMode.ReadWrite).Result.AsStream();
43             using (var zipArchive=new ZipArchive(zipStream,ZipArchiveMode.Read))
44             {
45                 ZipArchiveEntry entry = zipArchive.Entries[0];
46                 using (var stream=entry.Open())
47                 {
48                     while (stream.ReadByte()!=-1)
49                     {
50                         desFileStream.WriteByte((byte)stream.ReadByte());
51                     }
52                 }
53             }
54             desFileStream.Dispose();
55         }
56     }
View Code

方法内部适当调整,可用于Windows Phone.

posted @ 2012-11-27 14:51  denjuy  阅读(252)  评论(0编辑  收藏  举报