您的位置:首页 > 移动开发 > Unity3D

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

2015-09-06 13:40 531 查看
今天,我们来写写c#是如何通过代码解压缩文件的。

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

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

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

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

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

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

往事具备,只欠代码:

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

public static void DecompressToDirectory(string targetPath, string zipFilePath)//targetPath是我们解压到哪里,zipFilePath是我们的zip压缩文件目录(包括文件名和后缀)
{
if (File.Exists(zipFilePath))
{
var compressed = File.OpenRead(zipFilePath);
compressed.DecompressToDirectory(targetPath);
}
else
{
LoggerHelper.Error("Zip不存在: " + zipFilePath);
}
}


public static void DecompressToDirectory(this Stream source, string targetPath)//自己写stream的扩展方法,不懂的童鞋自行百度什么是扩展方法
{
targetPath = Path.GetFullPath(targetPath);
using (ZipInputStream decompressor = new ZipInputStream(source))
{
ZipEntry entry;

while ((entry = decompressor.GetNextEntry()) != null)
{
string name = entry.Name;
if (entry.IsDirectory && entry.Name.StartsWith("\\"))
name = entry.Name.ReplaceFirst("\\", "");

string filePath = Path.Combine(targetPath, name);
string directoryPath = Path.GetDirectoryName(filePath);

if (!string.IsNullOrEmpty(directoryPath) && !Directory.Exists(directoryPath))
Directory.CreateDirectory(directoryPath);

if (entry.IsDirectory)
continue;

byte[] data = new byte[2048];
using (FileStream streamWriter = File.Create(filePath))
{
int bytesRead;
while ((bytesRead = decompressor.Read(data, 0, data.Length)) > 0)
{
streamWriter.Write(data, 0, bytesRead);
}
}
}
}
}


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

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

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

[b]OK,讲完解压文件,我们来讲讲压缩文件。其实也和解压文件类似,都是通过文件流来进行处理:[/b]

/// <summary>
/// 压缩文件
/// </summary>
/// <param name="filePath">zip文件路径</param>
/// <param name="zipPath">压缩到哪个文件路径</param>
public static void ZipFile(string filePath, string zipPath)
{
if (!File.Exists(filePath))
{
Debug.LogError("需要压缩的文件不存在");
}
string zipFileName = zipPath  + Path.GetFileNameWithoutExtension(filePath) + ".zip";
Debug.Log(zipFileName);
using (FileStream fs = File.Create(zipFileName))
{
using (ZipOutputStream zipStream = new ZipOutputStream(fs))
{
using (FileStream stream = new FileStream(filePath, FileMode.Open, FileAccess.Read))
{
string fileName = Path.GetFileName(filePath);
ZipEntry zipEntry = new ZipEntry(fileName);
zipStream.PutNextEntry(zipEntry);
byte[] buffer = new byte[1024];
int sizeRead = 0;
try
{
do
{
sizeRead = stream.Read(buffer, 0, buffer.Length);
zipStream.Write(buffer, 0, sizeRead);
} while (sizeRead > 0);
}catch(Exception e)
{
Debug.LogException(e);
}
stream.Close();
}
zipStream.Finish();
zipStream.Close();
}
fs.Close();
}
}


  
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: