Files
plugin-library/Assets/Main/HotfixUpdateScript/Runtime/HotUpdate/Tools/ZipTool.cs

98 lines
3.4 KiB
C#
Raw Normal View History

2025-05-23 18:26:47 +08:00
using System;
using System.Collections.Generic;
using System.IO;
using System.IO.Compression;
using Cysharp.Threading.Tasks;
using UnityEngine;
using UnityEngine.Networking;
namespace Stary.Evo
{
public class ZipTool
{
// 新增:带进度回调的下载解压方法
2025-05-30 14:52:53 +08:00
public static async UniTask DownloadAndUnzipAsync(string fildId, string extractPath,
2025-05-23 18:26:47 +08:00
Action<float> downloadProgress = null, Action<float> unzipProgress = null)
{
string tempPath = Path.Combine(Application.persistentDataPath, "temp.zip");
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
try
{
2025-05-30 14:52:53 +08:00
string url = $"{AppConfig.IpConfig}/FileLoad/Download/{fildId}";
await WebRequestSystem.GetFile(url, tempPath,downloadProgress);
2025-05-23 18:26:47 +08:00
// 解压下载的文件
2025-05-30 14:52:53 +08:00
await UnzipAsync(tempPath, extractPath, unzipProgress);
File.Delete(tempPath);
2025-05-23 18:26:47 +08:00
}
finally
{
// 清理临时文件
if (File.Exists(tempPath))
{
File.Delete(tempPath);
}
}
}
// 修改:添加进度回调参数
2025-05-30 14:52:53 +08:00
public static async UniTask UnzipAsync(string zipPath, string extractPath,
2025-05-23 18:26:47 +08:00
Action<float> progressCallback = null)
{
try
{
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
using (ZipArchive archive = ZipFile.OpenRead(zipPath))
{
float totalEntries = archive.Entries.Count;
float processed = 0;
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
foreach (ZipArchiveEntry entry in archive.Entries)
{
string filePath = Path.Combine(extractPath, entry.FullName);
Directory.CreateDirectory(Path.GetDirectoryName(filePath));
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
if (!string.IsNullOrEmpty(entry.Name))
{
using (Stream inputStream = entry.Open())
using (FileStream outputStream = File.Create(filePath))
{
await inputStream.CopyToAsync(outputStream);
}
}
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
processed++;
float progress = processed / totalEntries;
progressCallback?.Invoke(progress);
}
}
Debug.Log($"解压完成: {extractPath}");
}
catch (Exception ex)
{
Debug.LogError($"解压失败: {ex.Message}");
throw;
}
}
2025-05-30 14:52:53 +08:00
2025-05-23 18:26:47 +08:00
/// <summary>
/// 自定义网络请求器需要登录
/// </summary>
/// <param name="url"></param>
/// <returns></returns>
private static UnityWebRequest WebRequester(string url)
{
var request = new UnityWebRequest(url, UnityWebRequest.kHttpVerbGET);
2025-05-30 14:52:53 +08:00
var authorization = GetAuthorization(AppConfig.UserName, AppConfig.PassWord);
2025-05-23 18:26:47 +08:00
request.SetRequestHeader("AUTHORIZATION", authorization);
return request;
}
private static string GetAuthorization(string userName, string password)
{
string auth = userName + ":" + password;
var bytes = System.Text.Encoding.GetEncoding("ISO-8859-1").GetBytes(auth);
return "Basic " + System.Convert.ToBase64String(bytes);
}
}
}