Unity使用SharpCompress压缩与解压缩文件

扶醉桌前 提交于 2020-03-07 04:30:21

工具类:

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

public static class Utils
{
    public static long CompressFile(string zipFile, string sourcefile, string fileName)
    {
        long size = 0;
        using (Stream s = File.OpenWrite(zipFile))
        {
            using (var ws = SharpCompress.Writer.WriterFactory.Open(s, SharpCompress.Common.ArchiveType.Zip, SharpCompress.Common.CompressionType.Deflate))
            {
                ws.Write(fileName, File.OpenRead(sourcefile), null);
            }
            size = s.Length;
        }
        return size;
    }

    public static long CompressFiles(string zipFile, List<string> files, int startPos, string profix)
    {
        long size = 0;
        using (Stream s = File.OpenWrite(zipFile))
        {
            using (var ws = SharpCompress.Writer.WriterFactory.Open(s, SharpCompress.Common.ArchiveType.Zip, SharpCompress.Common.CompressionType.Deflate))
            {
                foreach (var item in files)
                {
                    ws.Write(profix + item.Substring(startPos), File.OpenRead(item), null);
                }
            }
            size = s.Length;
        }
        return size;
    }

    public static bool UncompressMemory(string rootFloder, byte[] bytes)
    {
        using (var ms = new MemoryStream(bytes))
        {
            using (var ar = SharpCompress.Archive.ArchiveFactory.Open(ms))
            {
                foreach (var item in ar.Entries)
                {
                    if (!item.IsDirectory)
                    {
                        string file = rootFloder + item.FilePath;
                        string dir = Path.GetDirectoryName(file);
                        if (!Directory.Exists(dir)) Directory.CreateDirectory(dir);

                        using (FileStream fs = new FileStream(file, FileMode.Create))
                        {
                            item.WriteTo(fs);
                        }
                    }
                }
            }
        }
        return true;
    }

}

压缩

using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEditor;
using UnityEngine;

/// <summary>
/// 可以写进打包工具
/// 打包时自动压缩
/// </summary>
public class CompressTest
{
    static string filePath;
    static string zipPath;
    [MenuItem("Window/Test _F4")]
    static void Test()
    {
        filePath = Application.streamingAssetsPath+"/";
        zipPath = Application.streamingAssetsPath + "/视频.z";
        GenerateZip(filePath);
        AssetDatabase.Refresh();
    }
    #region 压缩
    /// <summary>
    /// 生成压缩包
    /// </summary>
    /// <param name="_orignaFloder"></param>
    static void GenerateZip(string _orignaFloder)
    {
        allFiles = new List<string>();
        GetAllFiles(_orignaFloder);
        if (File.Exists(zipPath))
            File.Delete(zipPath);
        AssetDatabase.Refresh();
        Utils.CompressFiles(zipPath, allFiles, _orignaFloder.LastIndexOf('/') + 1, "");
        System.Diagnostics.Process.Start(Path.GetDirectoryName(filePath));
    }
    static List<string> allFiles = null;
    /// <summary>
    /// 获取所有的资源
    /// </summary>
    /// <param name="path"></param>
    static void GetAllFiles(string path)
    {
        string[] dir = Directory.GetDirectories(path);
        DirectoryInfo fdir = new DirectoryInfo(path);
        FileInfo[] file = fdir.GetFiles();
        if (file.Length != 0 || dir.Length != 0)
        {
            foreach (FileInfo f in file)
            {
                if (!f.FullName.Contains(".meta"))
                {
                    allFiles.Add(f.FullName);
                }
            }
            foreach (string d in dir)
            {
                GetAllFiles(d);
            }
        }
    }
    #endregion
}

解压

using System;
using System.Collections;
using System.Collections.Generic;
using System.IO;
using UnityEngine;

/// <summary>
/// 运行项目,下载压缩文件并解压至指定目录
/// </summary>
public class ExtractZipTest : MonoBehaviour
{
    public static ExtractZipTest instance;
    public Action<string> onError;
    public Action onSuccess;

    /// <summary>
    /// 解压到此目录
    /// </summary>
    public string zipExtractFloder;
    /// <summary>
    /// 压缩包目录
    /// </summary>
    string orignalFilePath;
    private void Awake()
    {
        instance = this;
        zipExtractFloder = Application.streamingAssetsPath + "/";
        orignalFilePath = Application.streamingAssetsPath + "/视频.z";
        StartExtract();
    }
    public void StartExtract()
    {
        StartCoroutine(Extract(orignalFilePath));
    }

    IEnumerator Extract(string zipfile)
    {
        using (WWW www=new WWW(zipfile))
        {
            yield return www;
            if (www.error != null)
            {
                print("下载压缩包出错:" + www.error);
                onError?.Invoke(www.error);
            }
            else
            {
                print("下载压缩包成功:" + zipfile);
                string zipExtractPath = zipExtractFloder + Path.GetFileName(zipfile);
                using (FileStream fs=File.Create(zipExtractPath))
                {
                    fs.Write(www.bytes, 0, www.bytes.Length);
                }
                ExtractToStreaming(zipExtractPath);
            }
        }
    }

    void ExtractToStreaming(string filePath)
    {
        print("开始解压:" + filePath);
        byte[] bytes = File.ReadAllBytes(filePath);
        try
        {
            Utils.UncompressMemory(zipExtractFloder, bytes);
            onSuccess?.Invoke();
        }
        catch (Exception e)
        {
            print("解压失败:" + e.Message);
            onError?.Invoke(e.Message);
        }
    }
}

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!