解压缩文件
using System;
using System.Collections.Generic;
using System.IO;
using ICSharpCode.SharpZipLib.Checksums;
using ICSharpCode.SharpZipLib.Zip;
public static class ZipFileHelper
{
/// <summary>
/// 压缩文件
/// </summary>
/// <param name="path"></param>
/// <param name="zipFileName"></param>
public static void ZipFile(string path, string zipFileName)
{
if (string.IsNullOrEmpty(path) || string.IsNullOrEmpty(zipFileName))
return;
List<string> paths = new List<string>();
if (Directory.Exists(path))
{
foreach (var file in Directory.GetFiles(path, "*", SearchOption.AllDirectories))
{
paths.Add(file);
}
}
else if (File.Exists(path))
{
path = Path.GetFullPath(path);
paths.Add(path);
}
if (paths.Count == 0)
return;
ZipOutputStream outstream = null;
try
{
outstream = new ZipOutputStream(File.Create($"{zipFileName}.zip"));
outstream.SetLevel(6);
Crc32 crc = new Crc32();
foreach (var p in paths)
{
var file = p.Replace($@"{path}\", string.Empty);
var fs = File.OpenRead(p);
var buffer = new byte[fs.Length];
fs.Read(buffer, 0, buffer.Length);
var entry = new ZipEntry(file);
entry.DateTime = DateTime.Now;
entry.Size = fs.Length;
fs.Close();
crc.Reset();
crc.Update(buffer);
entry.Crc = crc.Value;
outstream.PutNextEntry(entry);
outstream.Write(buffer, 0, buffer.Length);
}
}
catch(Exception ex)
{
UnityEngine.Debug.LogError(ex);
}
finally
{
if (outstream != null)
{
outstream.Finish();
outstream.Close();
}
}
}
/// <summary>
/// 解压文件
/// </summary>
/// <param name="targetFile"></param>
/// <param name="decompressionPath"></param>
public static void UnZipFile(string targetFile, string decompressionPath)
{
if (string.IsNullOrEmpty(targetFile) || string.IsNullOrEmpty(decompressionPath))
return;
if (!File.Exists(targetFile))
return;
ZipInputStream inputstream=null;
ZipEntry entry;
int size = 2048;
byte[] data = new byte[2048];
try
{
inputstream = new ZipInputStream(File.OpenRead(targetFile));
while((entry = inputstream.GetNextEntry())!=null)
{
var path = Path.Combine(decompressionPath, entry.Name);
var dir = Path.GetDirectoryName(path);
if(!Directory.Exists(dir))
{
Directory.CreateDirectory(dir);
}
using (FileStream fs = File.Create(path))
{
while (true)
{
size = inputstream.Read(data, 0, data.Length);
if (size > 0)
{
fs.Write(data, 0, size);
}
else
{
break;
}
}
}
}
}
catch(Exception ex)
{
UnityEngine.Debug.LogError(ex);
}
finally
{
if(inputstream!=null)
{
inputstream.Close();
}
}
}
}