| 123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448 |
- using Microsoft.Win32;
- using SharpCompress.Archives;
- using SharpCompress.Archives.Rar;
- using SharpCompress.Archives.Zip;
- using SharpCompress.Common;
- using SharpCompress.Readers;
- using SharpCompress.Writers;
- using System;
- using System.Collections.Generic;
- using System.Diagnostics;
- using System.IO;
- using System.Linq;
- using System.Net.Http;
- using System.Text;
- using System.Threading.Tasks;
- using System.Web;
- namespace Masuit.Tools.Files
- {
- /// <summary>
- /// 7z压缩
- /// </summary>
- public class SevenZipCompressor : ISevenZipCompressor
- {
- private readonly HttpClient _httpClient;
- /// <summary>
- ///
- /// </summary>
- /// <param name="httpClientFactory"></param>
- public SevenZipCompressor(IHttpClientFactory httpClientFactory)
- {
- _httpClient = httpClientFactory.CreateClient();
- }
- /// <summary>
- /// 将多个文件压缩到一个文件流中,可保存为zip文件,方便于web方式下载
- /// </summary>
- /// <param name="files">多个文件路径,文件或文件夹,或网络路径http/https</param>
- /// <param name="rootdir"></param>
- /// <returns>文件流</returns>
- public MemoryStream ZipStream(List<string> files, string rootdir = "")
- {
- using (var archive = CreateZipArchive(files, rootdir))
- {
- var ms = new MemoryStream();
- archive.SaveTo(ms, new WriterOptions(CompressionType.Deflate)
- {
- LeaveStreamOpen = true,
- ArchiveEncoding = new ArchiveEncoding()
- {
- Default = Encoding.UTF8
- }
- });
- return ms;
- }
- }
- /// <summary>
- /// 压缩多个文件
- /// </summary>
- /// <param name="files">多个文件路径,文件或文件夹</param>
- /// <param name="zipFile">压缩到...</param>
- /// <param name="rootdir">压缩包内部根文件夹</param>
- public void Zip(List<string> files, string zipFile, string rootdir = "")
- {
- using (var archive = CreateZipArchive(files, rootdir))
- {
- archive.SaveTo(zipFile, new WriterOptions(CompressionType.Deflate)
- {
- LeaveStreamOpen = true,
- ArchiveEncoding = new ArchiveEncoding()
- {
- Default = Encoding.UTF8
- }
- });
- }
- }
- /// <summary>
- /// 解压rar文件
- /// </summary>
- /// <param name="rar">rar文件</param>
- /// <param name="dir">解压到...</param>
- /// <param name="ignoreEmptyDir">忽略空文件夹</param>
- public void UnRar(string rar, string dir = "", bool ignoreEmptyDir = true)
- {
- if (string.IsNullOrEmpty(dir))
- {
- dir = Path.GetDirectoryName(rar);
- }
- using (var archive = RarArchive.Open(rar))
- {
- var entries = ignoreEmptyDir ? archive.Entries.Where(entry => !entry.IsDirectory) : archive.Entries;
- foreach (var entry in entries)
- {
- entry.WriteToDirectory(dir, new ExtractionOptions()
- {
- ExtractFullPath = true,
- Overwrite = true
- });
- }
- }
- }
- /// <summary>
- /// 解压文件,自动检测压缩包类型
- /// </summary>
- /// <param name="compressedFile">rar文件</param>
- /// <param name="dir">解压到...</param>
- /// <param name="ignoreEmptyDir">忽略空文件夹</param>
- public void Decompress(string compressedFile, string dir = "", bool ignoreEmptyDir = true)
- {
- if (string.IsNullOrEmpty(dir))
- {
- dir = Path.GetDirectoryName(compressedFile);
- }
- using (Stream stream = File.OpenRead(compressedFile))
- {
- using (var reader = ReaderFactory.Open(stream))
- {
- while (reader.MoveToNextEntry())
- {
- if (ignoreEmptyDir)
- {
- reader.WriteEntryToDirectory(dir, new ExtractionOptions()
- {
- ExtractFullPath = true,
- Overwrite = true
- });
- }
- else
- {
- if (!reader.Entry.IsDirectory)
- {
- reader.WriteEntryToDirectory(dir, new ExtractionOptions()
- {
- ExtractFullPath = true,
- Overwrite = true
- });
- }
- }
- }
- }
- }
- }
- /// <summary>
- /// 创建zip包
- /// </summary>
- /// <param name="files"></param>
- /// <param name="rootdir"></param>
- /// <returns></returns>
- private ZipArchive CreateZipArchive(List<string> files, string rootdir)
- {
- var archive = ZipArchive.Create();
- var dic = GetFileEntryMaps(files);
- var remoteUrls = files.Distinct().Where(s => s.StartsWith("http")).Select(s =>
- {
- try
- {
- return new Uri(s);
- }
- catch (UriFormatException)
- {
- return null;
- }
- }).Where(u => u != null).ToList();
- foreach (var fileEntry in dic)
- {
- archive.AddEntry(Path.Combine(rootdir, fileEntry.Value), fileEntry.Key);
- }
- if (remoteUrls.Any())
- {
- //var dicList = remoteUrls.GroupBy(u => u.Authority).Select(g =>
- //{
- // if (g.Count() > 1)
- // {
- // string pathname = new string(g.First().AbsolutePath.Substring(0, g.Min(s => s.AbsolutePath.Length)).TakeWhile((c, i) => g.All(s => s.AbsolutePath[i] == c)).ToArray());
- // return g.ToDictionary(s => s, s => HttpUtility.UrlDecode(s.AbsolutePath.Substring(pathname.Length)));
- // }
- // return g.ToDictionary(s => s, s => Path.GetFileName(HttpUtility.UrlDecode(s.AbsolutePath)));
- //}).SelectMany(d => d).ToDictionary(x => x.Key, x => x.Value);
- Parallel.ForEach(remoteUrls, url =>
- {
- _httpClient.GetAsync(url).ContinueWith(async t =>
- {
- if (t.IsCompleted)
- {
- var res = await t;
- if (res.IsSuccessStatusCode)
- {
- Stream stream = await res.Content.ReadAsStreamAsync();
- //archive.AddEntry(Path.Combine(rootdir, pathDic[new Uri(url).AbsolutePath.Trim('/')]), stream);
- archive.AddEntry(Path.Combine(rootdir, Path.GetFileName(HttpUtility.UrlDecode(url.AbsolutePath))), stream);
- }
- }
- }).Wait();
- });
- }
- return archive;
- }
- /// <summary>
- /// 获取文件路径和zip-entry的映射
- /// </summary>
- /// <param name="files"></param>
- /// <returns></returns>
- private Dictionary<string, string> GetFileEntryMaps(List<string> files)
- {
- List<string> fileList = new List<string>();
- void GetFilesRecurs(string path)
- {
- //遍历目标文件夹的所有文件
- foreach (string fileName in Directory.GetFiles(path))
- {
- fileList.Add(fileName);
- }
- //遍历目标文件夹的所有文件夹
- foreach (string directory in Directory.GetDirectories(path))
- {
- GetFilesRecurs(directory);
- }
- }
- files.Where(s => !s.StartsWith("http")).ForEach(s =>
- {
- if (Directory.Exists(s))
- {
- GetFilesRecurs(s);
- }
- else
- {
- fileList.Add(s);
- }
- });
- if (!fileList.Any())
- {
- return new Dictionary<string, string>();
- }
- string dirname = new string(fileList.First().Substring(0, fileList.Min(s => s.Length)).TakeWhile((c, i) => fileList.All(s => s[i] == c)).ToArray());
- Dictionary<string, string> dic = fileList.ToDictionary(s => s, s => s.Substring(dirname.Length));
- return dic;
- }
- }
- /// <summary>
- /// SharpZip
- /// </summary>
- public static class SharpZip
- {
- #region 文件压缩
- /// <summary>
- /// 文件压缩
- /// </summary>
- /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
- /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
- public static void PackFiles(string filename, string directory)
- {
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
- }
- /// <summary>
- /// 文件压缩
- /// </summary>
- /// <param name="filename"> 压缩后的文件名(包含物理路径)</param>
- /// <param name="directory">待压缩的文件夹(包含物理路径)</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
- public static async void PackFilesAsync(string filename, string directory)
- {
- await Task.Delay(0);
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
- }
- #endregion
- #region 文件解压缩
- /// <summary>
- /// 文件解压缩
- /// </summary>
- /// <param name="file">待解压文件名(包含物理路径)</param>
- /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
- public static bool UnpackFiles(string file, string dir)
- {
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
- }
- /// <summary>
- /// 文件解压缩
- /// </summary>
- /// <param name="file">待解压文件名(包含物理路径)</param>
- /// <param name="dir"> 解压到哪个目录中(包含物理路径)</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
- public static async Task<bool> UnpackFilesAsync(string file, string dir)
- {
- await Task.Delay(0);
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
- }
- #endregion
- }
- /// <summary>
- /// ClassZip
- /// </summary>
- public static class ClassZip
- {
- #region 压缩
- /// <summary>
- /// 压缩
- /// </summary>
- /// <param name="fileToZip">待压缩的文件目录或文件</param>
- /// <param name="zipedFile">生成的目标文件</param>
- /// <param name="level">压缩级别,默认值6</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Zip方法替代")]
- public static bool Zip(string fileToZip, string zipedFile, int level = 6)
- {
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Zip方法替代");
- }
- /// <summary>
- /// 将多个文件压缩到一个文件流中,可保存为zip文件,方便于web方式下载
- /// </summary>
- /// <param name="files">多个文件路径,文件或文件夹</param>
- /// <returns>文件流</returns>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.ZipStream方法替代")]
- public static byte[] ZipStream(List<string> files)
- {
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.ZipStream方法替代");
- }
- #endregion
- #region 解压
- /// <summary>
- /// 解压
- /// </summary>
- /// <param name="fileToUpZip">待解压的文件</param>
- /// <param name="zipedFolder">解压目标存放目录</param>
- [Obsolete("该方法已过时,请使用SevenZipCompressor.Decompress方法替代")]
- public static void UnZip(string fileToUpZip, string zipedFolder)
- {
- throw new NotImplementedException("该方法已过时,请使用SevenZipCompressor.Decompress方法替代");
- }
- #endregion
- }
- /// <summary>
- /// WinRAR压缩操作
- /// </summary>
- public static class WinrarHelper
- {
- #region 压缩
- /// <summary>
- /// 压缩
- /// </summary>
- /// <param name="zipname">要解压的文件名</param>
- /// <param name="zippath">要压缩的文件目录</param>
- /// <param name="dirpath">初始目录</param>
- public static void Rar(string zipname, string zippath, string dirpath)
- {
- _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRAR.exe\Shell\Open\Command");
- if (_theReg != null)
- {
- _theObj = _theReg.GetValue("");
- _theRar = _theObj.ToString();
- _theReg?.Close();
- }
- _theRar = _theRar.Substring(1, _theRar.Length - 7);
- _theInfo = " a " + zipname + " " + zippath;
- _theStartInfo = new ProcessStartInfo
- {
- FileName = _theRar,
- Arguments = _theInfo,
- WindowStyle = ProcessWindowStyle.Hidden,
- WorkingDirectory = dirpath
- };
- _theProcess = new Process
- {
- StartInfo = _theStartInfo
- };
- _theProcess.Start();
- }
- #endregion
- #region 解压缩
- /// <summary>
- /// 解压缩
- /// </summary>
- /// <param name="zipname">要解压的文件名</param>
- /// <param name="zippath">要解压的文件路径</param>
- public static void UnRar(string zipname, string zippath)
- {
- _theReg = Registry.ClassesRoot.OpenSubKey(@"Applications\WinRar.exe\Shell\Open\Command");
- if (_theReg != null)
- {
- _theObj = _theReg.GetValue("");
- _theRar = _theObj.ToString();
- _theReg.Close();
- }
- _theRar = _theRar.Substring(1, _theRar.Length - 7);
- _theInfo = " X " + zipname + " " + zippath;
- _theStartInfo = new ProcessStartInfo
- {
- FileName = _theRar,
- Arguments = _theInfo,
- WindowStyle = ProcessWindowStyle.Hidden
- };
- _theProcess = new Process
- {
- StartInfo = _theStartInfo
- };
- _theProcess.Start();
- }
- #endregion
- #region 私有变量
- private static string _theRar;
- private static RegistryKey _theReg;
- private static object _theObj;
- private static string _theInfo;
- private static ProcessStartInfo _theStartInfo;
- private static Process _theProcess;
- #endregion
- }
- }
|