123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179 |
-
- using System;
- using System.IO;
- using ICSharpCode.SharpZipLib.Zip;
- using ICSharpCode.SharpZipLib.Core;
- using IES.ExamServer.DI.SignalRHost;
- using IES.ExamServer.Models;
- using Microsoft.AspNetCore.SignalR;
- using Microsoft.Extensions.Caching.Memory;
- using IES.ExamServer.Helper;
- namespace IES.ExamServer.Helpers
- {
- public static class ZipHelper
- {
- /*
- static void Main(string[] args)
- {
- string sourceDirectory = "path/to/your/source/directory";
- string zipFilePath = "protected.zip";
- string extractPath = "path/to/extract/folder";
- string password = "yourpassword";
- // 创建带密码的 ZIP 文件
- bool zipResult = ZipHelper.CreatePasswordProtectedZip(sourceDirectory, zipFilePath, password);
- if (zipResult)
- {
- Console.WriteLine("压缩成功!");
- }
- else
- {
- Console.WriteLine("压缩失败!");
- }
- // 解压带密码的 ZIP 文件
- bool extractResult = ZipHelper.ExtractPasswordProtectedZip(zipFilePath, extractPath, password);
- if (extractResult)
- {
- Console.WriteLine("解压成功!");
- }
- else
- {
- Console.WriteLine("解压失败!");
- }
- }
- */
- /// <summary>
- /// 创建带密码的 ZIP 文件
- /// </summary>
- /// <param name="sourceDirectory">要压缩的目录路径</param>
- /// <param name="zipFilePath">生成的 ZIP 文件路径</param>
- /// <param name="password">ZIP 文件密码</param>
- /// <returns>是否成功</returns>
- public static (bool res, string msg) CreatePasswordProtectedZip(string sourceDirectory, string zipFilePath, string password)
- {
- if (!Directory.Exists(sourceDirectory))
- {
- // Console.WriteLine("源目录不存在。");
- return (false, "源目录不存在。");
- }
- try
- {
- using (FileStream fsOut = File.Create(zipFilePath))
- using (ZipOutputStream zipStream = new ZipOutputStream(fsOut))
- {
- zipStream.SetLevel(0); // 设置压缩级别 (0-9)
- zipStream.Password = password; // 设置密码
- CompressFolder(sourceDirectory, zipStream, "");
- }
- //Console.WriteLine($"ZIP 文件已成功创建:{zipFilePath}");
- return (true, $"ZIP 文件已成功创建") ;
- }
- catch (Exception ex)
- {
- // Console.WriteLine($"创建 ZIP 文件时发生错误:{ex.Message}");
- return (false, $"创建 ZIP 文件时发生错误!");
- }
- }
- /// <summary>
- /// 解压带密码的 ZIP 文件
- /// </summary>
- /// <param name="zipFilePath">ZIP 文件路径</param>
- /// <param name="extractPath">解压目标目录</param>
- /// <param name="password">ZIP 文件密码</param>
- /// <returns>是否成功</returns>
- public static async Task<(bool res, string msg)> ExtractPasswordProtectedZip(string zipFilePath, string extractPath, string password,
- IHubContext<SignalRExamServerHub> _signalRExamServerHub,IMemoryCache _memoryCache,ILogger _logger,string deviceId, EvaluationClient evaluationClient)
- {
- if (!File.Exists(zipFilePath))
- {
- return (false, "ZIP 文件不存在。");
- }
- try
- {
- using (ZipInputStream zipInputStream = new ZipInputStream(File.OpenRead(zipFilePath)))
- {
- zipInputStream.Password = password; // 设置解压密码
- ZipEntry entry;
- long blobCount = evaluationClient.blobCount + 3;
- long currCount = 0 ;
- while ((entry = zipInputStream.GetNextEntry()) != null)
- {
- currCount++;
- string entryFileName = entry.Name;
- string fullPath = Path.Combine(extractPath, entryFileName);
- await _signalRExamServerHub.SendMessage(_memoryCache, _logger, deviceId, Constant._Message_grant_type_download_file,
- new MessageContent { dataId = evaluationClient.id, dataName = evaluationClient.name, messageType = Constant._Message_type_message, status = Constant._Message_status_success, content = $"[进度:{currCount}/[{blobCount}]],正在解压:{entryFileName}" });
- // 创建目录(如果条目是目录)
- string? directoryName = Path.GetDirectoryName(fullPath);
- if (!string.IsNullOrEmpty(directoryName) && !Directory.Exists(directoryName))
- {
- Directory.CreateDirectory(directoryName);
- }
- // 如果是文件,则解压文件
- if (!entry.IsDirectory)
- {
- using (FileStream streamWriter = File.Create(fullPath))
- {
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = zipInputStream.Read(buffer, 0, buffer.Length)) > 0)
- {
- streamWriter.Write(buffer, 0, bytesRead);
- }
- }
- }
- }
- }
- return (true, $"ZIP 文件已成功解压到:{extractPath}");
- }
- catch (Exception ex)
- {
- return (false, $"解压 ZIP 文件时发生错误:{ex.Message}");
- }
- }
- /// <summary>
- /// 递归压缩文件夹
- /// </summary>
- private static void CompressFolder(string path, ZipOutputStream zipStream, string folderName)
- {
- foreach (string file in Directory.GetFiles(path))
- {
- string fileName = Path.GetFileName(file);
- string relativePath = Path.Combine(folderName, fileName);
- ZipEntry entry = new ZipEntry(relativePath);
- entry.DateTime = DateTime.Now;
- zipStream.PutNextEntry(entry);
- using (FileStream fs = File.OpenRead(file))
- {
- byte[] buffer = new byte[4096];
- int bytesRead;
- while ((bytesRead = fs.Read(buffer, 0, buffer.Length)) > 0)
- {
- zipStream.Write(buffer, 0, bytesRead);
- }
- }
- zipStream.CloseEntry();
- }
- // 递归处理子目录
- foreach (string folder in Directory.GetDirectories(path))
- {
- string folderNameOnly = Path.GetFileName(folder);
- string newFolderName = Path.Combine(folderName, folderNameOnly);
- CompressFolder(folder, zipStream, newFolderName);
- }
- }
- }
- }
|