1、Unity下载Zip压缩文件主要使用UnityWebRequest类。
可以参考以下方法:
- webRequest = UnityWebRequest.Get(Path1); //压缩文件路径
- webRequest.timeout = 60;
- webRequest.downloadHandler = new DownloadHandlerBuffer();
-
- long fileSize = GetLocalFileSize(Path2); //存贮路径
- webRequest.SetRequestHeader("Range", "bytes=" + fileSize + "-");
-
- webRequest.SendWebRequest();
-
- while (!webRequest.isDone)
- {
- float progress = Mathf.Clamp01(webRequest.downloadProgress);
- progressBar.fillAmount = progress;
- progressText.text = string.Format("{0}%", Mathf.RoundToInt(progress * 100f));
-
- yield return null;
- }
-
- if (webRequest.isNetworkError || webRequest.isHttpError)
- {
- progressObj.SetActive(false);
- }
- else
- {
- byte[] downloadedData = webRequest.downloadHandler.data;
- File.WriteAllBytes(Path2, downloadedData);
- }
其中这里我还用个while循环写了个下载进度条。
2、解压Zip压缩文件用到的System.IO.Compression下的ZipFile.OpenRead()方法。
具体可以参考以下代码:
- /// <summary>
- /// 解压
- /// </summary>
- /// <param name="zipFilePath">压缩文件路径</param>
- /// <param name="extractPath">解压路径</param>
- public void ExtractZipFile(string zipFilePath, string extractPath)
- {
- using (ZipArchive archive = ZipFile.OpenRead(zipFilePath))
- {
- try
- {
- foreach (ZipArchiveEntry entry in archive.Entries)
- {
- string entryPath = Path.Combine(extractPath, entry.FullName);
-
- if (entry.Name == "")
- {
- Directory.CreateDirectory(entryPath);
- }
- else
- {
- entry.ExtractToFile(entryPath, true);
- }
- }
- }
- catch(Exception e)
- {
- UnityEngine.Debug.Log(e.Message);
-
- }
-
- }
- }