Unity应用中如何将选定文件打包为Zip文件夹?
在Unity中实现多文件打包为可解压的Zip文件夹
首先明确:GZipStream不适合你的需求——它只能压缩单个文件,没法创建包含多个文件、保留目录结构的标准Zip包,用户没法直接解压出完整的场景数据。
下面给两种实用的实现方案:
方案一:用.NET自带的ZipArchive(推荐,Unity 2018+可用)
Unity 2018及以上支持.NET 4.x等价子集,其中的ZipArchive类可以直接生成标准Zip包,不用额外装库。
步骤&代码:
- 先引用命名空间:
using System.IO; using System.IO.Compression;
- 打包多文件/目录的代码:
/// <summary> /// 把指定文件/目录打包成Zip /// </summary> /// <param name="zipPath">生成的Zip路径(比如Application.persistentDataPath + "/save.zip")</param> /// <param name="filesToZip">要打包的文件/目录路径列表</param> public void CreateZip(string zipPath, List<string> filesToZip) { // 先删掉已存在的旧Zip if (File.Exists(zipPath)) { File.Delete(zipPath); } // 创建并写入Zip包 using (var zipArchive = ZipFile.Open(zipPath, ZipArchiveMode.Create)) { foreach (var path in filesToZip) { if (File.Exists(path)) { // 用文件名作为Zip内的路径,避免打包绝对路径 var entryName = Path.GetFileName(path); zipArchive.CreateEntryFromFile(path, entryName, CompressionLevel.Optimal); } else if (Directory.Exists(path)) { // 递归打包整个目录,保留子文件夹结构 var dirInfo = new DirectoryInfo(path); foreach (var file in dirInfo.GetFiles("*", SearchOption.AllDirectories)) { // 计算文件相对于根目录的路径,保留结构 var relativePath = file.FullName.Substring(dirInfo.FullName.Length + 1); zipArchive.CreateEntryFromFile(file.FullName, relativePath, CompressionLevel.Optimal); } } } } }
- 解压Zip的测试代码(用户也能直接用系统解压工具打开):
/// <summary> /// 把Zip解压到指定目录 /// </summary> /// <param name="zipPath">Zip文件路径</param> /// <param name="extractPath">解压目标目录</param> public void ExtractZip(string zipPath, string extractPath) { if (!File.Exists(zipPath)) return; // 创建目标目录(不存在就新建) Directory.CreateDirectory(extractPath); // 解压整个Zip包 using (var zipArchive = ZipFile.OpenRead(zipPath)) { zipArchive.ExtractToDirectory(extractPath); } }
注意点:
- 去Unity的Player Settings > Other Settings里,把Api Compatibility Level改成
.NET 4.x或更高版本。 - 文件操作尽量用
Application.persistentDataPath,这是Unity官方推荐的可读写路径,跨平台都能用。
方案二:用第三方库SharpZipLib(适配老版本Unity)
如果你的Unity版本低于2018,不支持.NET 4.x,可以用SharpZipLib这个开源压缩库,它支持标准Zip格式。
步骤&代码:
- 下载SharpZipLib的Unity兼容dll,放到项目的
Plugins文件夹里。 - 打包代码示例:
using ICSharpCode.SharpZipLib.Zip; using System.IO; public void CreateZipWithSharpZipLib(string zipPath, List<string> filesToZip) { using (var fs = File.Create(zipPath)) using (var zipStream = new ZipOutputStream(fs)) { zipStream.SetLevel(9); // 压缩等级0-9,9是最高压缩率 foreach (var path in filesToZip) { if (File.Exists(path)) { var entryName = Path.GetFileName(path); var zipEntry = new ZipEntry(entryName) { DateTime = DateTime.Now }; zipStream.PutNextEntry(zipEntry); // 读取文件并写入Zip using (var fileStream = File.OpenRead(path)) { byte[] buffer = new byte[4096]; int bytesRead; while ((bytesRead = fileStream.Read(buffer, 0, buffer.Length)) > 0) { zipStream.Write(buffer, 0, bytesRead); } } zipStream.CloseEntry(); } // 目录递归打包的逻辑可以参考方案一自行扩展 } } }
内容的提问来源于stack exchange,提问作者Ivan
相关产品推荐
相关产品推荐

