WP7 ZIP 压缩与解压缩

来源:互联网 发布:r语言数据分类 编辑:程序博客网 时间:2024/06/06 07:05

WP7 ZIP 压缩与解压缩

今天我要做一个简单的 WP7 下的 zip 压缩一个文件与解压缩一个文件 如图:

 

主要任务是将一个XML 文件压缩,然后在解压缩出来!

WP7 平台下有一个开源工具 http://slsharpziplib.codeplex.com/

这个开源工具已经支持大部分的压缩标准,其它标准可以看他的示例

 

压缩代码

?
privatevoidButton_Zip_Tap(objectsender, GestureEventArgs e)
        {
            try
            {
                DelFile(SavePathZip);
                using(var store = IsolatedStorageFile.GetUserStoreForApplication())
                {
                    using(var streamOut = newZipOutputStream(store.OpenFile(SavePathZip, FileMode.Create)))
                    {
                        streamOut.SetLevel(9);
                        using(var streamIn = (App.GetResourceStream(newUri(FilePath, UriKind.Relative)).Stream))
                        {
                            stringnewName = ZipEntry.CleanName(FilePath);
                            ZipEntry newEntry = newZipEntry(newName);//必须设置此对象才能压缩否则报错
                            newEntry.Size = streamIn.Length;
                            newEntry.DateTime = DateTime.Now;
                            streamOut.PutNextEntry(newEntry);
                            streamIn.CopyTo(streamOut);
                            streamOut.Flush();
                            streamOut.Finish();
                            text.Text = "压缩成功!"+"     压缩率:" + ((float)streamOut.Length / (float)streamIn.Length) * 100 + "%";
                        }
                    }
                }
            }
            catch(Exception ex)
            {
                text.Text = "压缩失败!"+ ex.Message;
            }
        }

 

解压缩代码

  

 try
{
DelFile(UnZipFilePath);
using (var store = IsolatedStorageFile.GetUserStoreForApplication())
{
using (ZipInputStream streamIn = new ZipInputStream(store.OpenFile(SavePathZip, FileMode.Open)))
{
ZipEntry theEntry = streamIn.GetNextEntry();//必须调用这个才能 Read

if (theEntry != null)
{
string fileName = theEntry.Name;
if (fileName != String.Empty)
{
text.Text = new StreamReader(streamIn).ReadToEnd();
}
}
}
}
}
catch (Exception ex)
{
text.Text = "解压缩失败!" + ex.Message;
}
}
复制代码

 

做这个时候有个小问题就是TextBlock 不能完全显示 解压缩的文件,起初我还以为是读取的字节流有问题,结果发现问题在TextBlock 

,目前WP7上TextBlock空间的宽和高上限为2048px,超过这个数值的内容将被截断。由于高宽有上限,所以TextBlock显示的字符长度还与字体大小有关。解决办法为截取字符然后在一个或多个TextBlock上显示。

 

当然上面的例子为单个文件的压缩与解压缩!

如果要做文件 的压缩 就要自己写个循环 压缩子文件夹下的所有文件

源码下载地址:http://download.csdn.net/detail/happyq/4062962