Unity3d通用工具类之解压缩文件 | 您所在的位置:网站首页 › 解压缩是干嘛的 › Unity3d通用工具类之解压缩文件 |
那么这里呢,我用的是第三发的压缩库,这个是用到一个dll,也就是ICSharpCode.SharpZipLib.Zip.dll 链接: ICSharpCode.SharpZipLib.dll_免费高速下载|百度网盘-分享无限制 这里是Zip的解压方式 /// /// 扩展类 /// public static class Utils { /// /// 解压文件 /// /// 解压位置 /// zip压缩文件目录(包括文件名和后缀) public static void DecompressToDirectory(string targetPath, string zipFilePath) { if (File.Exists(zipFilePath)) { var compressed = File.OpenRead(zipFilePath); compressed.DecompressToDirectory(targetPath); } else { Debug.LogError($"Zip不存在: {zipFilePath}"); } } public static void DecompressToDirectory(this Stream source, string targetPath) { 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.Replace("\\", ""); 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); } } } Debug.Log("解压完成"); } } }使用代码:Utils.DecompressToDirectory(targetPath, zipFileName); 压缩文件其实也和解压文件类似,都是通过文件流来进行处理: /// /// 压缩文件 /// /// zip文件路径 /// 压缩到哪个文件路径 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(); } } |
CopyRight 2018-2019 实验室设备网 版权所有 |