Silverlight 的解压缩之Zip in Zip

.Net下的经典的SharpZipLib已经发布Silverlight4版本,可以到Codeplex下载。

如何创建在Zip中在创建Zip内,这个需求非常好,因为Silverlight现在还没有类似Select Folder Dialog。

1. 定义SaveFileDialog …

说废话,遭人骂


2. 获取File stream 并传递给 ZipOutputStream (zip的流),创建rootZipStream

             if (SaveFileDialog.ShowDialog().Value)

            {

                System.IO.Stream fileStream = SaveFileDialog .OpenFile();

                ZipOutputStream rootZipStream = new ZipOutputStream(fileStream);

                rootZipStream .SetLevel(6);   // 常规的压缩比

                rootZipStream .IsStreamOwner = true;

                …..


3. 定义ZipEntry (相当于里面的Zip里面的一个文件),构造函数就是文件名,其实就是定义一个FileInfo。将你的数据转换为bytes。(网上方法超多)

                    bytes[] buffer = …

                    ZipEntry jpgEntry = new ZipEntry(FileName)

                    {

                        DateTime = DateTime.Now,

                        Size = buffer.Length

                    };


4. 定义内部的ZipOutputStream,同上,不过要传入一个空的MemoryStream。

                    MemoryStream innerZipStream = new MemoryStream();

                    ZipOutputStream innerZip = new ZipOutputStream(innerZipStream);

                    innerZip.SetLevel(6);

                    innerZip.IsStreamOwner = true;


5. 将你的byte[]们对应的ZipEntry 们 交给innerZipStream

                    innerZip.PutNextEntry(docEntry);

                    innerZip.Write(docBuffer, 0, docBuffer.Length);

 

                    innerZip.PutNextEntry(jpgEntry);

                    innerZip.Write(jpgBuffer, 0, jpgBuffer.Length); // 有几个传几个

                    innerZip.Finish(); // 这个别忘记,否则就出现 “压缩末端不可预料”什么玩意,呵呵


6. 为innerZipStream创建ZipEntry,交给rootZipStream。最后Finish and Close

                    ZipEntry innerZipEntry = new ZipEntry(string.Format("{0}.zip", yourInnerZipName))
                    {
                        DateTime = DateTime.Now,
                        Size = innerZip.Length
                    };

                    rootZip.PutNextEntry(innerZipEntry);

                    rootZip.Write(
                        this.StreamToBuffer(innerZipStream),
                        0,
                        (int)innerZipStream.Length);

                    innerZipStream.Close();

 

                    rootZipStream.Finish();
                    rootZipStream.Close();


 

总之,原理很简单,很多细节要注意,呵呵。 转载注明出处哦 O(∩_∩)O~

posted @ 2010-09-01 16:52  Silver_Throne  阅读(1607)  评论(4编辑  收藏  举报