码迷,mamicode.com
首页 > 编程语言 > 详细

Unity3d通用工具类之解压缩文件

时间:2015-09-06 14:27:28      阅读:279      评论:0      收藏:0      [点我收藏+]

标签:

今天,我们来写写c#是如何通过代码解压缩文件的。

 

在游戏的项目中呢,常常我们需要运用到解压缩的技术。比如,当游戏需要更新的时候,我们会从服务器中下载更新的压缩文件包。

 

这时候我们就需要解压文件,然后覆盖添加到游戏文件夹去,实现游戏的更新。

 

通常我们就需要通过代码来实现这一功能。

 

那么这里呢,我用的是第三发的压缩库,这个是用到一个dll,也就是ICSharpCode.SharpZipLib.Zip.dll

 

读者可以自行百度下载,这里我提供链接给你们:

 

http://pan.baidu.com/s/1ntqx6cT

 

往事具备,只欠代码:

 

我们先来讲讲怎么解压文件,这里我只写Zip的解压方式,其实只要掌握一种解压技术就行。

 

 1         public static void DecompressToDirectory(string targetPath, string zipFilePath)//targetPath是我们解压到哪里,zipFilePath是我们的zip压缩文件目录(包括文件名和后缀)
 2         {
 3             if (File.Exists(zipFilePath))
 4             {
 5                 var compressed = File.OpenRead(zipFilePath);
 6                 compressed.DecompressToDirectory(targetPath);
 7             }
 8             else
 9             {
10                 LoggerHelper.Error("Zip不存在: " + zipFilePath);
11             }
12         }
 1         public static void DecompressToDirectory(this Stream source, string targetPath)//自己写stream的扩展方法,不懂的童鞋自行百度什么是扩展方法
 2         {
 3             targetPath = Path.GetFullPath(targetPath);
 4             using (ZipInputStream decompressor = new ZipInputStream(source))
 5             {
 6                 ZipEntry entry;
 7 
 8                 while ((entry = decompressor.GetNextEntry()) != null)
 9                 {
10                     string name = entry.Name;
11                     if (entry.IsDirectory && entry.Name.StartsWith("\\"))
12                         name = entry.Name.ReplaceFirst("\\", "");
13 
14                     string filePath = Path.Combine(targetPath, name);
15                     string directoryPath = Path.GetDirectoryName(filePath);
16 
17                     if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
18                         Directory.CreateDirectory(directoryPath);
19 
20                     if (entry.IsDirectory)
21                         continue;
22 
23                     byte[] data = new byte[2048];
24                     using (FileStream streamWriter = File.Create(filePath))
25                     {
26                         int bytesRead;
27                         while ((bytesRead = decompressor.Read(data, 0, data.Length)) > 0)
28                         {
29                             streamWriter.Write(data, 0, bytesRead);
30                         }
31                     }
32                 }
33             }
34         }

 

ok,代码写完了,同样,我们放到Utils通用工具类内。

 

只需要一句代码:Utils.DecompressToDirectory(targetPath, zipFileName);

 

就可以实现文件的解压啦!是不是很简单!

Unity3d通用工具类之解压缩文件

标签:

原文地址:http://www.cnblogs.com/CaomaoUnity3d/p/4785314.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!