Unity 下载Zip压缩文件并且解压缩

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()方法。

具体可以参考以下代码:

    /// 
    /// 解压
    /// 
    /// 压缩文件路径
    /// 解压路径
    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);        
                
            }           
            
        }
    }

你可能感兴趣的:(unity,c#,游戏引擎)