1. 程式人生 > >Unity下載並解壓網路資源

Unity下載並解壓網路資源

using ICSharpCode.SharpZipLib.Zip;
using SimpleFramework;
using System;
using System.Collections;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO;
using System.Net;
using UnityEngine;

public class NewBehaviourScript : MonoBehaviour
{

    // Update is called once per frame
    void Update()
    {
        if (Input.GetKeyDown(KeyCode.W))
        {
            string url = "http://anq-resources.oss-cn-shanghai.aliyuncs.com/anq/Lua.zip";
            string currDownFile = @"D:/";
            string fileName = DownloadFile(url, currDownFile);
            if (!String.IsNullOrEmpty(fileName))
            {
                UnityEngine.Debug.Log("檔案下載成功,檔名稱:" + fileName);
            }
            else
            {
                UnityEngine.Debug.Log("檔案下載失敗");
            }
        }
    }
   
    public static string DownloadFile(string url,string path)
    {
        try
        {
            string fileName = CreateFileName(url);
            if (!Directory.Exists(path))
            {
                Directory.CreateDirectory(path);
            }
            WebClient client = new WebClient();
            client.DownloadFileAsync(new System.Uri(url), path + fileName);
            return fileName;
        }
        catch
        {
            return "";
        }
    }
    public static string CreateFileName(string url)
    {
        string fileName = "";
        string fileExt = url.Substring(url.LastIndexOf(".")).Trim().ToLower();
        System.Random rnd = new System.Random();
        //fileName = "Lua" + fileExt;
        fileName = DateTime.Now.ToString("yyyyMMddHHmmssfff") + rnd.Next(10, 99).ToString() + fileExt;
        return fileName;
    }
    //*************************下載並解壓
    IEnumerator Wait_LoadDown(string ZipID, string url)
    {
        WWW www = new WWW(url);
        yield return www;
        if (www.isDone)
        {
            if (www.error == null)
            {
                yield return new WaitForEndOfFrame();
                //直接使用 將byte轉換為Stream,省去先儲存到本地在解壓的過程
                SaveZip(ZipID, url, www.bytes);

            }
            else
            {
                UnityEngine.Debug.Log(www.error);
            }
        }
    }
    /// <summary> 
    /// 解壓功能(下載後直接解壓壓縮檔案到指定目錄) 
    /// </summary> 
    /// <param name="wwwStream">www下載轉換而來的Stream</param> 
    /// <param name="zipedFolder">指定解壓目標目錄(每一個Obj對應一個Folder)</param> 
    /// <param name="password">密碼</param> 
    /// <returns>解壓結果</returns> 
    public static bool SaveZip(string ZipID, string url, byte[] ZipByte, string password = null)
    {
        bool result = true;
        FileStream fs = null;
        ZipInputStream zipStream = null;
        ZipEntry ent = null;
        string fileName;


        UnityEngine.Debug.Log(ZipID);

        if (!Directory.Exists(ZipID))
        {
            Directory.CreateDirectory(ZipID);
        }
        try
        {
            //直接使用 將byte轉換為Stream,省去先儲存到本地在解壓的過程
            Stream stream = new MemoryStream(ZipByte);
            zipStream = new ZipInputStream(stream);

            if (!string.IsNullOrEmpty(password))
            {
                zipStream.Password = password;
            }
            while ((ent = zipStream.GetNextEntry()) != null)
            {
                if (!string.IsNullOrEmpty(ent.Name))
                {
                    fileName = Path.Combine(ZipID, ent.Name);

                    #region      Android
                    fileName = fileName.Replace('\\', '/');

                    if (fileName.EndsWith("/"))
                    {
                        Directory.CreateDirectory(fileName);
                        continue;
                    }
                    #endregion
                    fs = File.Create(fileName);

                    int size = 2048;
                    byte[] data = new byte[size];
                    while (true)
                    {
                        size = zipStream.Read(data, 0, data.Length);
                        if (size > 0)
                        {
                            //fs.Write(data, 0, data.Length);
                            fs.Write(data, 0, size);//解決讀取不完整情況
                        }
                        else
                            break;
                    }
                }
            }
        }
        catch (Exception e)
        {
            UnityEngine.Debug.Log(e.ToString());
            result = false;
        }
        finally
        {
            if (fs != null)
            {
                fs.Close();
                fs.Dispose();
            }
            if (zipStream != null)
            {
                zipStream.Close();
                zipStream.Dispose();
            }
            if (ent != null)
            {
                ent = null;
            }
            GC.Collect();
            GC.Collect(1);
        }
        return result;
    }
}