123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304 |
- using System;
- using System.Collections.Generic;
- using System.Linq;
- using System.Text;
- using System.IO;
- using System.IO.Packaging;
- using Ionic.Zip;
- using Bowin.Common.Log;
- using SevenZip;
- using System.Collections;
- namespace Bowin.Common
- {
- public class ZIPHelper
- {
- public static IList<string> ExtractFile(string zipFilePath, string targetPath)
- {
- IList<string> result = new List<string>();
- using (Package zip = Package.Open(zipFilePath, FileMode.OpenOrCreate))
- {
- var parts = zip.GetParts();
- foreach (var part in parts)
- {
- var stream = part.GetStream();
- byte[] buffer = new byte[stream.Length + 100];
- long total = 0;
- for (int offset = 0; ; )
- {
- int bytesRead = stream.Read(buffer, offset, 100);
- if (bytesRead == 0) break;
- offset += bytesRead;
- total += bytesRead;
- }
- string filePath = targetPath + @"\" + Path.GetFileName(part.Uri.LocalPath);
- var fileStream = File.Create(filePath);
- for (int offset = 0; ; )
- {
- if (total - (offset + 1) > 100)
- {
- fileStream.Write(buffer, offset, 100);
- offset += 100;
- }
- else
- {
- fileStream.Write(buffer, offset, Convert.ToInt32(total - (offset + 1)));
- fileStream.Flush();
- break;
- }
- }
- result.Add(filePath);
- }
- }
- return result;
- }
- /// <summary>
- /// 解压缩.z文件
- /// </summary>
- /// <param name="rarFilePath"></param>
- /// <returns></returns>
- public static IList<string> ExtractZFile(string zFilePath, string outPutPath)
- {
- LogHelper.WriteLog(LogType.ServiceLog, "----进入ExtractZFile解压方法-----");
- IList<string> result = new List<string>();
- System.Diagnostics.Process proc = new System.Diagnostics.Process();
- string pathOf7Zip = System.Configuration.ConfigurationManager.AppSettings["PathOf7Zip"];
- if (System.Web.HttpContext.Current != null)
- {
- pathOf7Zip = System.Web.HttpContext.Current.Server.MapPath("~/") + pathOf7Zip;
- }
- else
- {
- pathOf7Zip = System.AppDomain.CurrentDomain.BaseDirectory + pathOf7Zip;
- }
- proc.StartInfo.FileName = pathOf7Zip;
- proc.StartInfo.CreateNoWindow = true;
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.RedirectStandardOutput = true;
- proc.StartInfo.RedirectStandardInput = true;
- proc.StartInfo.Arguments = "l " + zFilePath;
- LogHelper.WriteLog(LogType.ServiceLog, "----" + proc.StartInfo.Arguments + "-----");
- //bool currentIsFile = false;
- try
- {
- proc.Start();
- if (proc.StandardOutput.EndOfStream)
- {
- throw new Exception("系统错误!");
- }
- //string buffer = proc.StandardOutput.ReadLine();
- //if (fileText.IndexOf(".jpg") > 0)
- //{
- // currentIsFile = !currentIsFile;
- // if (currentIsFile)
- // {
- // LogHelper.WriteLog(LogType.ServiceLog, "----result.ADD:" + outPutPath + @"\" + fileText.Split(' ').Last() + "-----");
- // result.Add(outPutPath + @"\" + fileText.Split(' ').Last());
- // }
- //}
- string allbuffer = proc.StandardOutput.ReadToEnd();
- proc.WaitForExit();
- LogHelper.WriteLog(LogType.ServiceLog, "**allbuffer:" + allbuffer + "**");
- var phyIndex = allbuffer.IndexOf("Physical Size");
- string tText = allbuffer.Substring(phyIndex);
- string Text1 = tText.Substring(tText.IndexOf("\r\n") + 4);
- string Text2 = Text1.Substring(Text1.IndexOf("\r\n") + 4);
- string Text3 = Text2.Substring(Text2.IndexOf("\r\n") + 4);
- string Text4 = Text3.Remove(Text3.LastIndexOf("\r\n"));
- string Text5 = Text4.Remove(Text4.LastIndexOf("\r\n"));
- string Text6 = Text5.Remove(Text5.LastIndexOf("\r\n"));
- string Text7 = Text6.Replace("\r\n", "#");
- List<string> fileList = Text7.Split('#').ToList();
- foreach (var filestring in fileList)
- {
- result.Add(outPutPath + @"\" + filestring.Split(' ').Last());
- }
- //if (!proc.WaitForExit(3600000))
- //{
- //}
- proc = new System.Diagnostics.Process();
- proc.StartInfo.FileName = pathOf7Zip;
- proc.StartInfo.CreateNoWindow = true;
- proc.StartInfo.UseShellExecute = false;
- proc.StartInfo.RedirectStandardOutput = false;
- proc.StartInfo.RedirectStandardInput = false;
- proc.EnableRaisingEvents = true;
- proc.StartInfo.Arguments = "e -y -o" + outPutPath + " " + zFilePath;
- proc.Start();
- proc.WaitForExit();
- proc.Close();
- }
- catch (Exception ex)
- {
- LogHelper.WriteLog(LogType.ServiceLog, "Error:" + ex.Message);
- Exception MyEx = new Exception("解压缩出错!" + ex.Message);
- }
- foreach (var a in result)
- {
- LogHelper.WriteLog(LogType.ServiceLog, "----" + a + "-----");
- }
- proc.Dispose();
- return result;
- }
- public static IList<string> Extract7ZFile(string zFilePath, string outPutPath)
- {
- using (FileStream istream = new FileStream(zFilePath, FileMode.Open, FileAccess.Read))
- {
- if (IntPtr.Size == 4)
- {
- SevenZipCompressor.SetLibraryPath(System.Web.HttpContext.Current.Server.MapPath("~/bin/x86/") + @"7z.dll");
- }
- else
- {
- SevenZipCompressor.SetLibraryPath(System.Web.HttpContext.Current.Server.MapPath("~/bin/x64/") + @"7z.dll");
- }
- SevenZipExtractor extractor = new SevenZipExtractor(istream);
- extractor.ExtractArchive(outPutPath); // 全部解压到指定目录
- using (FileStream ostream = new FileStream(outPutPath, FileMode.Create, FileAccess.Write))
- {
- extractor.ExtractFile(0, ostream); // 流式解压指定文件
- }
- }
- return new List<string>();
- }
- public static List<string> SevenZip_ExtractStream(string zFilePath, string outPutPath)
- {
- var nameKey = Guid.NewGuid().ToString();
- var fileStream = new FileStream(zFilePath, FileMode.Open, FileAccess.Read);
- var data = new byte[fileStream.Length];
- fileStream.Read(data, 0, data.Length);
- // 直接读取 Stream流格式会报错,所以暂时做一个转义(先临时保存)
- // Invalid archive: open/read error! Is it encrypted and a wrong password was provided?
- // If your archive is an exotic one, it is possible that SevenZipSharp has no signature for its format and thus decided it is TAR by mistake.
- var tmpZipFullName = CreateTmpFile(data, nameKey);
- if (IntPtr.Size == 4)
- {
- var path = System.Web.HttpContext.Current.Server.MapPath("~/bin/x86/") + "7z.dll";
- SevenZipCompressor.SetLibraryPath(path);
- }
- else
- {
- var path = System.Web.HttpContext.Current.Server.MapPath("~/bin/x64/") + @"7z.dll";
- SevenZipCompressor.SetLibraryPath(path);
- }
- using (var zip = new SevenZipExtractor(tmpZipFullName))
- {
- // 解压所有文件到指定目录
- zip.ExtractArchive(outPutPath);
- // 解压单个文件到指定目录
- // zip.ExtractFiles(targetDirectory, 包内的文件索引或者文件名);
- // 包内单个文件读取到字节缓冲区
- //foreach (var entry in zip.ArchiveFileData)
- //{
- // using (var memoryStream = new MemoryStream())
- // {
- // zip.ExtractFile(entry.FileName, memoryStream);
- // var entryBuffer = new byte[memoryStream.Length];
- // memoryStream.Position = 0;
- // memoryStream.Read(entryBuffer, 0, entryBuffer.Length);
- // }
- //}
- // 解压单个文件到指定目录(允许改文件名,以流方式写入)
- //foreach (var entry in zip.ArchiveFileData)
- // {
- // var newFullName = System.Web.HttpContext.Current.Server.MapPath("~/Content/DownFile6/") + entry.FileName;
- // var newPath = Path.GetDirectoryName(newFullName);
- // if (!string.IsNullOrWhiteSpace(newPath) && !Directory.Exists(newPath))
- // Directory.CreateDirectory(newPath);
- // using (var fs = new FileStream(newFullName, FileMode.OpenOrCreate, FileAccess.Write))
- // {
- // zip.ExtractFile(entry.FileName, fs); // 将包内的文件以流的方式写入
- // }
- // }
- } // enf.of using (var zip = new SevenZipExtractor(tmpZipFullName))
- List<string> list = GetAllFilesbyFolder(outPutPath, "*.jpg", true);
- return list;
- }
- private static string CreateTmpFile(byte[] data, string nameKey)
- {
- // 直接读取 Stream流格式会报错,所以暂时做一个转义(先临时保存)
- // Invalid archive: open/read error! Is it encrypted and a wrong password was provided?
- // If your archive is an exotic one, it is possible that SevenZipSharp has no signature for its format and thus decided it is TAR by mistake.
- var dir = System.Web.HttpContext.Current.Server.MapPath("~/Content/DownFile/");
- var baseFolder = dir + Path.DirectorySeparatorChar + "TmpZip" + Path.DirectorySeparatorChar;
- if (!System.IO.Directory.Exists(baseFolder))
- {
- Directory.CreateDirectory(baseFolder);
- }
- var tmpZipFullName = string.Format("{0}{1}_{2}.zip", baseFolder, DateTime.Now.ToString("yyyy_MM_dd_HH_mm_ss_fff"), nameKey);
- if (System.IO.File.Exists(tmpZipFullName))
- {
- System.IO.File.Delete(tmpZipFullName);
- }
- using (var fs1 = new FileStream(tmpZipFullName, FileMode.Create, FileAccess.Write))
- {
- fs1.Write(data, 0, data.Length);
- }
- return tmpZipFullName;
- }
- /// <summary>
- ///
- /// </summary>
- /// <param name="foldername">文件夹名</param>
- /// <param name="filefilter">文件名筛选</param>
- /// <param name="iscontainsubfolder">是否读取后代文件夹中的文件</param>
- /// <returns></returns>
- public static List<string> GetAllFilesbyFolder(string foldername, string filefilter, bool iscontainsubfolder)
- {
- List<string> resarray = new List<string>();
- var files = Directory.GetFiles(foldername, filefilter);
- for (int i = 0; i < files.Length; i++)
- {
- resarray.Add(files[i]);
- }
- if (iscontainsubfolder)
- {
- string[] folders = Directory.GetDirectories(foldername);
- for (int j = 0; j < folders.Length; j++)
- {
- //遍历所有文件夹
- List<string> temp = GetAllFilesbyFolder(folders[j], filefilter, iscontainsubfolder);
- resarray.AddRange(temp);
- }
- }
- return resarray;
- }
- public static string PackageDirectory(string path)
- {
- using (ZipFile zipNew = new ZipFile())
- {
- var pathName = Path.GetFileName(path.TrimEnd('\\'));
- var fileInfos = Directory.GetFiles(path);
- zipNew.UseUnicodeAsNecessary = true;
- //zipNew.
- // add this map file into the "images" directory in the zip archive
- //zip.AddFile("c:\\images\\personal\\7440-N49th.png", "images");
- //// add the report into a different directory in the archive
- //zip.AddFile("c:\\Reports\\2008-Regional-Sales-Report.pdf", "files");
- foreach (var fileInfo in fileInfos)
- {
- zipNew.AlternateEncodingUsage = ZipOption.AsNecessary;
- zipNew.AlternateEncoding = Encoding.Unicode;
- zipNew.AddFile(fileInfo, @"\");
- }
- zipNew.Save(pathName + ".zip");
- return path.TrimEnd('\\') + "\\" + pathName + ".zip";
- }
- }
- }
- }
|