You cannot select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

172 lines
4.4 KiB
C#

using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.IO.Compression;
using System.Linq;
using System.Text;
using System.Text.Unicode;
using System.Threading.Tasks;
using SharpCompress.Common;
using SharpCompress.Factories;
using SharpCompress.Writers;
using SharpCompress.Compressors;
using SharpCompress.Archives;
using SharpCompress.Archives.Zip;
using SharpCompress.Archives.Rar;
using SharpCompress.Archives.GZip;
using SharpCompress.Archives.Tar;
using SharpCompress.Archives.SevenZip;
namespace SharpCompressStudy.Core
{
public static class CommonUtility
{
/// <summary>
/// 解压文件
/// </summary>
/// <param name="fileName">压缩文件包</param>
/// <param name="isDelete">解压后删除压缩文件</param>
public static void Decompress(string fileName, bool isDelete)
{
var extName = Path.GetExtension(fileName).Trim().ToLower();
switch (extName)
{
case ".rar":
DecompressRarFile(fileName, isDelete);
break;
case ".zip":
DecompressZipFile(fileName, isDelete);
break;
case ".gzip":
DecompressGzipFile(fileName, isDelete);
break;
case ".gz":
DecompressGzFile(fileName, isDelete);
break;
default:
break;
}
if (isDelete)
{
File.Delete(fileName);
}
}
private static void DecompressRarFile(string fileName, bool isDelete)
{
try
{
var extName = Path.GetExtension(fileName).Trim().ToLower();
switch (extName)
{
case ".rar":
break;
default:
break;
}
if (isDelete)
{
File.Delete(fileName);
}
}
catch (Exception ex)
{
Console.Write($"解压报错,错误:{ex}");
throw;
}
}
private static void DecompressZipFile(string fileName, bool isDelete)
{
try
{
ExtractionOptions options = new ExtractionOptions();
//抽取顶级目录
var extractPath = Directory.GetParent(fileName)?.FullName + "22";
if (!Directory.Exists(extractPath))
{
Directory.CreateDirectory(extractPath);
}
var archive = ArchiveFactory.Open(fileName);
foreach (var entry in archive.Entries)
{
//加密的
if (entry.IsEncrypted)
{
continue;
}
if (entry.IsDirectory)
{
}
else
{
entry.WriteToDirectory(extractPath, new ExtractionOptions() { ExtractFullPath = true, Overwrite = true });
}
}
if (isDelete)
{
File.Delete(fileName);
}
}
catch (Exception ex)
{
Console.Write($"解压报错,错误:{ex.Message}");
throw;
}
}
private static void DecompressGzipFile(string fileName, bool isDelete)
{
try
{
if (isDelete)
{
File.Delete(fileName);
}
}
catch (Exception ex)
{
Console.Write($"解压报错,错误:{ex}");
throw;
}
}
private static void DecompressGzFile(string fileName, bool isDelete)
{
try
{
if (isDelete)
{
File.Delete(fileName);
}
}
catch (Exception ex)
{
Console.Write($"解压报错,错误:{ex}");
throw;
}
}
}
}