public void Compress(string sourceFilename, string targetFilename, FileMode fileMode, OutArchiveFormat archiveFormat, CompressionMethod compressionMethod, CompressionLevel compressionLevel, ZipEncryptionMethod zipEncryptionMethod, string password, int bufferSize, int preallocationPercent, bool check, Dictionary<string, string> customParameters) { bufferSize *= this._sectorSize; SevenZipCompressor compressor = new SevenZipCompressor(); compressor.FastCompression = true; compressor.ArchiveFormat = archiveFormat; compressor.CompressionMethod = compressionMethod; compressor.CompressionLevel = compressionLevel; compressor.DefaultItemName = Path.GetFileName(sourceFilename); compressor.DirectoryStructure = false; compressor.ZipEncryptionMethod = zipEncryptionMethod; foreach (var pair in customParameters) { compressor.CustomParameters[pair.Key] = pair.Value; } using (FileStream sourceFileStream = new FileStream(sourceFilename, FileMode.Open, FileAccess.Read, FileShare.None, bufferSize, Win32.FileFlagNoBuffering | FileOptions.SequentialScan)) { using (FileStream targetFileStream = new FileStream(targetFilename, fileMode, FileAccess.ReadWrite, FileShare.ReadWrite, 8, FileOptions.WriteThrough | Win32.FileFlagNoBuffering)) { this.Compress(compressor, sourceFileStream, targetFileStream, password, preallocationPercent, check, bufferSize); } } }
public static void CompressDirectory(string compressDirectory, string archFileName, OutArchiveFormat archiveFormat, CompressionLevel compressionLevel) { SevenZipCompressor.SetLibraryPath(LibraryPath); SevenZipCompressor cmp = new SevenZipCompressor(); cmp.ArchiveFormat = archiveFormat; cmp.CompressionLevel = compressionLevel; cmp.BeginCompressDirectory(compressDirectory, archFileName); }
private static void InitUserOutFormat(object user, OutArchiveFormat format) { if (!_outArchives.ContainsKey(user)) { _outArchives.Add(user, new Dictionary <OutArchiveFormat, IOutArchive>()); } if (!_outArchives[user].ContainsKey(format)) { _outArchives[user].Add(format, null); _totalUsers++; } }
/// <summary> /// Gets IOutArchive interface to pack 7-zip archives. /// </summary> /// <param name="format">Archive format.</param> /// <param name="user">Archive format user.</param> public static IOutArchive OutArchive(OutArchiveFormat format, object user) { lock (_syncRoot) { if (_outArchives[user][format] == null) { #if !WINCE && !MONO var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); if (_modulePtr == IntPtr.Zero) { throw new SevenZipLibraryException(); } var createObject = (NativeMethods.CreateObjectDelegate) Marshal.GetDelegateForFunctionPointer( NativeMethods.GetProcAddress(_modulePtr, "CreateObject"), typeof(NativeMethods.CreateObjectDelegate)); if (createObject == null) { throw new SevenZipLibraryException(); } #endif object result; Guid interfaceId = #if !WINCE && !MONO typeof(IOutArchive).GUID; #else new Guid(((GuidAttribute)typeof(IOutArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value); #endif Guid classID = Formats.OutFormatGuids[format]; try { #if !WINCE && !MONO createObject(ref classID, ref interfaceId, out result); #elif !MONO NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result); #else result = SevenZip.Mono.Factory.CreateInterface <IOutArchive>(classID, interfaceId, user); #endif } catch (Exception) { throw new SevenZipLibraryException("Your 7-zip library does not support this archive type."); } InitUserOutFormat(user, format); _outArchives[user][format] = result as IOutArchive; } return(_outArchives[user][format]); #if !WINCE && !MONO } #endif }
/// <summary> /// 7z压缩 /// </summary> /// <param name="sourceFiles">文件路径集合</param> /// <param name="destFileName">压缩后的文件路径</param> /// <param name="password">压缩密码</param> /// <param name="compressionMode">压缩模式</param> /// <param name="outArchiveFormat">压缩格式</param> /// <param name="compressionLevel">压缩级别</param> /// <param name="fileCompressionStarted">压缩开始事件</param> /// <param name="filesFound">文件发现事件</param> /// <param name="compressing">压缩进度事件</param> /// <param name="fileCompressionFinished">压缩完成事件</param> /// <returns>压缩结果</returns> public static bool CompressTo7z( List <string> sourceFiles, string destFileName, string password = null, CompressionMode compressionMode = CompressionMode.Create, OutArchiveFormat outArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel compressionLevel = CompressionLevel.High, EventHandler <FileNameEventArgs> fileCompressionStarted = null, EventHandler <IntEventArgs> filesFound = null, EventHandler <ProgressEventArgs> compressing = null, EventHandler <EventArgs> fileCompressionFinished = null) { var tmp = new SevenZipCompressor { CompressionMode = compressionMode, ArchiveFormat = outArchiveFormat, CompressionLevel = compressionLevel }; if (fileCompressionStarted != null) { tmp.FileCompressionStarted += fileCompressionStarted; } if (filesFound != null) { tmp.FilesFound += filesFound; } if (compressing != null) { tmp.Compressing += compressing; } if (fileCompressionFinished != null) { tmp.FileCompressionFinished += fileCompressionFinished; } var files = sourceFiles?.Where(o => File.Exists(o))?.ToArray(); if (files?.Length > 0) { if (!string.IsNullOrEmpty(password)) { tmp.CompressFilesEncrypted(destFileName, password, files); } else { tmp.CompressFiles(destFileName, files); } return(true); } return(false); }
/// <summary> /// Constructor /// </summary> /// <param name="pArchiveStream">Stream for the archive file</param> /// <param name="pPassword">Password (optional)</param> /// <param name="pEncryptHeaders">Encrypt headers of the archive</param> /// <param name="pArchiveFormat">Format of the archive</param> /// <param name="pCompressionLevel">Level of compression</param> /// <param name="pCompressionMethod">Compression method</param> public SevenZipArchiver(Stream pArchiveStream, string pPassword = null, bool pEncryptHeaders = false, OutArchiveFormat pArchiveFormat = OutArchiveFormat.Zip, CompressionLevel pCompressionLevel = CompressionLevel.Normal, CompressionMethod pCompressionMethod = CompressionMethod.Default) { ArchiveStream = pArchiveStream; Password = pPassword; EncryptHeaders = pEncryptHeaders; ArchiveFormat = pArchiveFormat; CompressionLevel = pCompressionLevel; CompressionMethod = pCompressionMethod; Source = SevenZipArchiverSource.Stream; }
// ------------------------------------------------------------------------------------------ /// <summary> /// Constructor /// </summary> /// <param name="pArchiveName">Path to the archive file</param> /// <param name="pPassword">Password (optional)</param> /// <param name="pEncryptHeaders">Encrypt headers of the archive</param> /// <param name="pArchiveFormat">Format of the archive</param> /// <param name="pCompressionLevel">Level of compression</param> /// <param name="pCompressionMethod">Compression method</param> public SevenZipArchiver(string pArchiveName, string pPassword = null, bool pEncryptHeaders = false, OutArchiveFormat pArchiveFormat = OutArchiveFormat.Zip, CompressionLevel pCompressionLevel = CompressionLevel.Normal, CompressionMethod pCompressionMethod = CompressionMethod.Default) { ArchiveName = pArchiveName?.Trim(); Password = pPassword; EncryptHeaders = pEncryptHeaders; ArchiveFormat = pArchiveFormat; CompressionLevel = pCompressionLevel; CompressionMethod = pCompressionMethod; Source = SevenZipArchiverSource.File; }
private void Delete(OutArchiveFormat archiveFormat, string archivePath, Func <string, bool> filter) { Dictionary <int, string> fileDictionary = new Dictionary <int, string>(); foreach (var foundItem in lookup(getExtractor(archivePath, null), filter)) { fileDictionary.Add(foundItem.Value1, null); } if (fileDictionary.Count > 0) { SevenZipCompressor compressor = getCompressor(archiveFormat); compressor.ModifyArchive(archivePath, fileDictionary); } }
private static bool CompressionBenchmark(Stream inStream, Stream outStream, OutArchiveFormat format, CompressionMethod method, ref LibraryFeature?features, LibraryFeature testedFeature) { try { var compressor = new SevenZipCompressor { ArchiveFormat = format, CompressionMethod = method }; compressor.CompressStream(inStream, outStream); } catch (Exception) { return(false); } features |= testedFeature; return(true); }
/// <summary> /// /// </summary> /// <param name="fileAndDirectoryFullPaths">The full path to all the files and directorys to compress or archives to extract</param> /// <param name="archivefullPath">The path where to place the archive or the extracted files and directorys</param> /// <param name="format">The compression format(only for compression)</param> /// <param name="fastcompression">If you whan to compresss the files fast(only for compression)</param> /// <param name="password">(only for compression and if required)</param> /// <param name="compresstionlevel">How strong must the compression be (only for compression)</param> public ArchiveProcressScreen(IList <String> fileAndDirectoryFullPaths, string archivefullPath, ArchiveAction action, string archivename = null, OutArchiveFormat format = OutArchiveFormat.SevenZip, bool fastcompression = false, string password = null, CompressionLevel compresstionlevel = CompressionLevel.Normal) { SevenZipBase.SetLibraryPath(IntPtr.Size == 8? "7z64.dll" : "7z32.dll"); InitializeComponent(); _fileAndDirectoryFullPaths = fileAndDirectoryFullPaths; _archivePath = archivefullPath; _archivename = archivename; _action = action; _format = format; _compresstionlevel = compresstionlevel; _password = password; _fastcompression = fastcompression; _deltatotaal = pb_totaalfiles.Value += (int)(100 / fileAndDirectoryFullPaths.Count); tempPath = string.Format("{0}//7zip//", Path.GetTempPath()); pb_compression.Value = 0; pb_totaalfiles.Value = 0; }
/// <summary> /// /// </summary> /// <param name="fileAndDirectoryFullPaths">The full path to all the files and directorys to compress or archives to extract</param> /// <param name="archivefullPath">The path where to place the archive or the extracted files and directorys</param> /// <param name="format">The compression format(only for compression)</param> /// <param name="fastcompression">If you whan to compresss the files fast(only for compression)</param> /// <param name="password">(only for compression and if required)</param> /// <param name="compresstionlevel">How strong must the compression be (only for compression)</param> public ArchiveProcressScreen(IList<String> fileAndDirectoryFullPaths, string archivefullPath, ArchiveAction action, string archivename = null, OutArchiveFormat format = OutArchiveFormat.SevenZip, bool fastcompression = false, string password = null, CompressionLevel compresstionlevel = CompressionLevel.Normal) { SevenZipBase.SetLibraryPath(IntPtr.Size == 8 ? "7z64.dll" : "7z32.dll"); InitializeComponent(); _fileAndDirectoryFullPaths = fileAndDirectoryFullPaths; _archivePath = archivefullPath; _archivename = archivename; _action = action; _format = format; _compresstionlevel = compresstionlevel; _password = password; _fastcompression = fastcompression; _deltatotaal = pb_totaalfiles.Value += (int)(100 / fileAndDirectoryFullPaths.Count); tempPath = $"{Path.GetTempPath()}//7zip//"; pb_compression.Value = 0; pb_totaalfiles.Value = 0; }
public void Modify(string archivePath, string orginalPath, string destName, bool isFolder, IProgress <FileExplorer.Defines.ProgressEventArgs> progress = null) { OutArchiveFormat archiveFormat = SevenZipWrapper.getArchiveFormat(archivePath); string srcParentPath = FileExplorer.Models.PathHelper.Disk.GetDirectoryName(orginalPath); string destPath = FileExplorer.Models.PathHelper.Disk.Combine(srcParentPath, destName); orginalPath = orginalPath.TrimEnd('\\'); var dic = lookup(getExtractor(archivePath), isFolder ? orginalPath + "\\*" : orginalPath).ToDictionary(tup => tup.Value1, tup => FileExplorer.Models.PathHelper.Disk.Combine(destPath, tup.Value2.Substring(orginalPath.Length))); if (dic.Count() > 0) { SevenZipCompressor compressor = getCompressor(archiveFormat, null, progress); compressor.ModifyArchive(archivePath, dic); } }
/// <summary> /// Gets IOutArchive interface to pack 7-zip archives. /// </summary> /// <param name="format">Archive format.</param> /// <param name="user">Archive format user.</param> public static IOutArchive OutArchive(OutArchiveFormat format, object user) { lock (_syncRoot) { if (_outArchives[user][format] == null) { #if NET45 || NETSTANDARD2_0 var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); #endif if (_modulePtr == IntPtr.Zero) { throw new SevenZipLibraryException(); } var createObject = (NativeMethods.CreateObjectDelegate) Marshal.GetDelegateForFunctionPointer( NativeMethods.GetProcAddress(_modulePtr, "CreateObject"), typeof(NativeMethods.CreateObjectDelegate)); var interfaceId = typeof(IOutArchive).GUID; try { var classId = Formats.OutFormatGuids[format]; createObject(ref classId, ref interfaceId, out var result); InitUserOutFormat(user, format); _outArchives[user][format] = result as IOutArchive; } catch (Exception) { throw new SevenZipLibraryException("Your 7-zip library does not support this archive type."); } } return(_outArchives[user][format]); } }
private void GetFormatFromString(string ft) { switch (ft) { case "ZIP (.zip)": format = OutArchiveFormat.Zip; ext = ".zip"; break; case "7ZIP (.7z)": format = OutArchiveFormat.SevenZip; ext = ".7z"; break; case "BZIP2 (.bz2)": format = OutArchiveFormat.BZip2; ext = ".bz2"; break; case "GZIP (.gz)": format = OutArchiveFormat.GZip; ext = ".gz"; break; case "TAR (.tar)": format = OutArchiveFormat.Tar; ext = ".tar"; break; case "XZ (.xz)": format = OutArchiveFormat.XZ; ext = ".xz"; break; default: break; } UpdateOutputLabel(); }
private bool createSevenZipPackage(string password, OutArchiveFormat format) { bool success = false; log.Info($"Using SevenZip library to create a package with format [{format}]"); if (this.overwrite) { deleteIfExist(this.dstFileName); } SevenZipBase.SetLibraryPath(get7ZipDllPath()); SevenZipCompressor zcomp = new SevenZipCompressor(); zcomp.ArchiveFormat = format; try { if (String.IsNullOrEmpty(password)) { log.Warn($"No password was supplied, so the output file will be unencrypted [{this.dstFileName}]"); zcomp.CompressFiles(this.dstFileName, this.srcFileList.ToArray()); } else { zcomp.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; log.Info("Enabled ZIP AES_256 encryption"); zcomp.EncryptHeaders = true; zcomp.CompressFilesEncrypted(this.dstFileName, password, this.srcFileList.ToArray()); } } catch (Exception e) { log.Error($"Exception while trying to pack with SevenZipCompressor", e); return(false); } log.Info($"Successfully packed the files into [{this.dstFileName}]"); return(success); }
private SevenZipCompressor getCompressor(OutArchiveFormat archiveFormat, string password = null, IProgress <FileExplorer.Defines.ProgressEventArgs> progress = null) { SevenZipCompressor compressor = new SevenZipCompressor(); compressor.DirectoryStructure = true; compressor.ArchiveFormat = archiveFormat; compressor.CompressionMode = CompressionMode.Append; if (progress != null) { string workingFile = null; compressor.Compressing += (o, e) => { var args = new FileExplorer.Defines.ProgressEventArgs(e.PercentDone, 100, workingFile); progress.Report(args); if (args.Cancel) { e.Cancel = true; } }; compressor.FileCompressionStarted += (o, e) => { workingFile = e.FileName; var args = new FileExplorer.Defines.ProgressEventArgs(e.PercentDone, 100, workingFile); progress.Report(args); if (args.Cancel) { e.Cancel = true; } }; } return(compressor); }
protected override void BeginProcessing() { base.BeginProcessing(); _inferredOutArchiveFormat = GetInferredOutArchiveFormat(); switch (ParameterSetName) { case ParameterSetNames.NoPassword: _password = null; break; case ParameterSetNames.PlainPassword: _password = Password; break; case ParameterSetNames.SecurePassword: _password = Utils.SecureStringToString(SecurePassword); break; default: throw new Exception($"Unsupported parameter set {ParameterSetName}"); } if (EncryptFilenames.IsPresent) { if (_inferredOutArchiveFormat != OutArchiveFormat.SevenZip) { throw new ArgumentException("Encrypting filenames is supported for 7z format only."); } if (string.IsNullOrEmpty(_password)) { throw new ArgumentException("Encrypting filenames is supported only when using a password."); } } }
public CreateArchive(IList<string> fileAndDirectoryFullPaths, bool compress, string archivePath, OutArchiveFormat defaultFormat = OutArchiveFormat.SevenZip, bool only = true) { InitializeComponent(); _fileAndDirectoryFullPaths = fileAndDirectoryFullPaths; txt_archivePath.Text = archivePath; if (compress) { rbtn_extract.Enabled = only; } else { rbtn_compress.Enabled = only; } rbtn_compress.Checked = compress; rbtn_extract.Checked = !compress; txt_archivename.Text = Path.GetFileNameWithoutExtension(fileAndDirectoryFullPaths.First().Split('\\').Last()); CreateGroepBoxEnum(typeof(OutArchiveFormat), gb_format); SetEnum(gb_format, defaultFormat.ToString()); CreateGroepBoxEnum(typeof(CompressionLevel), gb_compressionlevel); SetEnum(gb_compressionlevel, CompressionLevel.Normal.ToString()); }
protected string stPackDirectory(string dir, string name, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { Log.Trace("stPackDirectory: `{0}` -> `{1}` : type({2}), method({3}), level({4})", dir, name, type, method, rate); if (String.IsNullOrWhiteSpace(dir)) { throw new InvalidArgumentException("The path to directory is empty."); } if (String.IsNullOrWhiteSpace(name)) { throw new InvalidArgumentException("The output name of archive is empty."); } string fullpath = location(dir); // additional checking of input directory. // The SevenZipSharp creates empty file of archive even if the input directory is not exist o_O if (!Directory.Exists(fullpath)) { throw new NotFoundException("Directory `{0}` is not found. Looked as `{1}`", dir, fullpath); } SevenZipCompressor zip = new SevenZipCompressor() { ArchiveFormat = type, CompressionMethod = method, CompressionLevel = rate, CompressionMode = CompressionMode.Create, FastCompression = true, // to disable some events inside SevenZip IncludeEmptyDirectories = true }; compressDirectory(zip, fullpath, location(name)); return(Value.Empty); }
private string SelectExtention(OutArchiveFormat format) { switch (format) { case OutArchiveFormat.Zip: { return(OutArchiveFormat.Zip.ToString().ToLower()); } case OutArchiveFormat.XZ: { return(OutArchiveFormat.XZ.ToString().ToLower()); } case OutArchiveFormat.Tar: { return(OutArchiveFormat.Tar.ToString().ToLower()); } case OutArchiveFormat.SevenZip: { return("7z"); } case OutArchiveFormat.GZip: { return("gz"); } case OutArchiveFormat.BZip2: { return("bz2"); } } return(OutArchiveFormat.Zip.ToString().ToLower()); }
private string SelectExtention(OutArchiveFormat format) { switch (format) { case OutArchiveFormat.Zip: return OutArchiveFormat.Zip.ToString().ToLower(); case OutArchiveFormat.XZ: return OutArchiveFormat.XZ.ToString().ToLower(); case OutArchiveFormat.Tar: return OutArchiveFormat.Tar.ToString().ToLower(); case OutArchiveFormat.SevenZip: return "7z"; case OutArchiveFormat.GZip: return "gz"; case OutArchiveFormat.BZip2: return "bz2"; } return OutArchiveFormat.Zip.ToString().ToLower(); }
/// <summary> /// Loads the grouped setting values from the persistent store. /// </summary> public override void Load() { ModCompressionLevel = EnvironmentInfo.Settings.ModCompressionLevel; ModCompressionFormat = EnvironmentInfo.Settings.ModCompressionFormat; }
protected string stPackFiles(Argument[] files, string name, Argument[] except, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { Log.Trace("stPackFiles: `{0}` : type({1}), method({2}), level({3})", name, type, method, rate); if(String.IsNullOrWhiteSpace(name)) { throw new InvalidArgumentException("The output name of archive is empty."); } if(files.Length < 1) { throw new InvalidArgumentException("List of files is empty."); } if(files.Any(p => p.type != ArgumentType.StringDouble)) { throw new InvalidArgumentException("Incorrect data from input files. Define as {\"f1\", \"f2\", ...}"); } if(except != null && except.Any(p => p.type != ArgumentType.StringDouble)) { throw new InvalidArgumentException("Incorrect data from the 'except' argument. Define as {\"f1\", \"f2\", ...}"); } // additional checking of input files. // The SevenZipSharp creates directories if input file is not exist o_O string[] input = files.Select((f, i) => pathToFile((string)f.data, i)).ToArray().ExtractFiles(); #if DEBUG Log.Trace("stPackFiles: Found files `{0}`", String.Join(", ", input)); #endif if(except != null) { input = input.Except(except .Where(f => !String.IsNullOrWhiteSpace((string)f.data)) .Select(f => location((string)f.data)) .ToArray() .ExtractFiles() ).ToArray(); } if(input.Length < 1) { throw new InvalidArgumentException("The input files was not found. Check your mask and the exception list if used."); } SevenZipCompressor zip = new SevenZipCompressor() { ArchiveFormat = type, CompressionMethod = method, CompressionLevel = rate, CompressionMode = CompressionMode.Create, FastCompression = true, // to disable some events inside SevenZip DirectoryStructure = true, }; compressFiles(zip, location(name), input); return Value.Empty; }
private static void InitUserOutFormat(object user, OutArchiveFormat format) { if (!_outArchives.ContainsKey(user)) { _outArchives.Add(user, new Dictionary<OutArchiveFormat, IOutArchive>()); } if (!_outArchives[user].ContainsKey(format)) { _outArchives[user].Add(format, null); _totalUsers++; } }
protected string stPackFiles(Argument[] files, string name, Argument[] except, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { Log.Trace("stPackFiles: `{0}` : type({1}), method({2}), level({3})", name, type, method, rate); if (String.IsNullOrWhiteSpace(name)) { throw new InvalidArgumentException("The output name of archive is empty."); } if (files.Length < 1) { throw new InvalidArgumentException("List of files is empty."); } if (files.Any(p => p.type != ArgumentType.StringDouble)) { throw new InvalidArgumentException("Incorrect data from input files. Define as {\"f1\", \"f2\", ...}"); } if (except != null && except.Any(p => p.type != ArgumentType.StringDouble)) { throw new InvalidArgumentException("Incorrect data from the 'except' argument. Define as {\"f1\", \"f2\", ...}"); } // additional checking of input files. // The SevenZipSharp creates directories if input file is not exist o_O string[] input = files.Select((f, i) => pathToFile((string)f.data, i)).ToArray().ExtractFiles(); #if DEBUG Log.Trace("stPackFiles: Found files `{0}`", String.Join(", ", input)); #endif if (except != null) { input = input.Except(except .Where(f => !String.IsNullOrWhiteSpace((string)f.data)) .Select(f => location((string)f.data)) .ToArray() .ExtractFiles() ).ToArray(); } if (input.Length < 1) { throw new InvalidArgumentException("The input files was not found. Check your mask and the exception list if used."); } SevenZipCompressor zip = new SevenZipCompressor() { ArchiveFormat = type, CompressionMethod = method, CompressionLevel = rate, CompressionMode = CompressionMode.Create, FastCompression = true, // to disable some events inside SevenZip DirectoryStructure = true, }; compressFiles(zip, location(name), input); return(Value.Empty); }
/// <summary> /// コンストラクタ /// </summary> /// <param name="sevenZipLibraryPath"><c>7z.dll</c>へのパス</param> /// <param name="format">現状<c>SevenZip</c>と<c>Zip</c>のみ対応</param> public SevenZipCompressor(string sevenZipLibraryPath, OutArchiveFormat format) { SevenZipBase.SetLibraryPath(sevenZipLibraryPath); ArchiveFormat = format; }
/// <summary> /// 7z压缩 /// </summary> /// <param name="sourcePath">文件或者文件夹路径</param> /// <param name="destFileName">压缩后的文件路径</param> /// <param name="password">压缩密码</param> /// <param name="compressionMode">压缩模式</param> /// <param name="outArchiveFormat">压缩格式</param> /// <param name="compressionLevel">压缩级别</param> /// <param name="fileCompressionStarted">压缩开始事件</param> /// <param name="filesFound">文件发现事件</param> /// <param name="compressing">压缩进度事件</param> /// <param name="fileCompressionFinished">压缩完成事件</param> /// <returns>压缩结果</returns> public static bool CompressTo7z( string sourcePath, string destFileName, string password = null, CompressionMode compressionMode = CompressionMode.Create, OutArchiveFormat outArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel compressionLevel = CompressionLevel.High, EventHandler <FileNameEventArgs> fileCompressionStarted = null, EventHandler <IntEventArgs> filesFound = null, EventHandler <ProgressEventArgs> compressing = null, EventHandler <EventArgs> fileCompressionFinished = null) { var tmp = new SevenZipCompressor { CompressionMode = compressionMode, ArchiveFormat = outArchiveFormat, CompressionLevel = compressionLevel }; if (fileCompressionStarted != null) { tmp.FileCompressionStarted += fileCompressionStarted; } if (filesFound != null) { tmp.FilesFound += filesFound; } if (compressing != null) { tmp.Compressing += compressing; } if (fileCompressionFinished != null) { tmp.FileCompressionFinished += fileCompressionFinished; } //文件夹 if (Directory.Exists(sourcePath)) { if (password.IsNotNullOrEmpty()) { tmp.CompressDirectory(sourcePath, destFileName, password); } else { tmp.CompressDirectory(sourcePath, destFileName); } return(true); } //文件 else if (File.Exists(sourcePath)) { if (password.IsNotNullOrEmpty()) { tmp.CompressFilesEncrypted(destFileName, password, sourcePath); } else { tmp.CompressFiles(destFileName, sourcePath); } return(true); } return(false); }
protected string stPackDirectory(string dir, string name, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { Log.Trace("stPackDirectory: `{0}` -> `{1}` : type({2}), method({3}), level({4})", dir, name, type, method, rate); if(String.IsNullOrWhiteSpace(dir)) { throw new InvalidArgumentException("The path to directory is empty."); } if(String.IsNullOrWhiteSpace(name)) { throw new InvalidArgumentException("The output name of archive is empty."); } string fullpath = location(dir); // additional checking of input directory. // The SevenZipSharp creates empty file of archive even if the input directory is not exist o_O if(!Directory.Exists(fullpath)) { throw new NotFoundException("Directory `{0}` is not found. Looked as `{1}`", dir, fullpath); } SevenZipCompressor zip = new SevenZipCompressor() { ArchiveFormat = type, CompressionMethod = method, CompressionLevel = rate, CompressionMode = CompressionMode.Create, FastCompression = true, // to disable some events inside SevenZip IncludeEmptyDirectories = true }; compressDirectory(zip, fullpath, location(name)); return Value.Empty; }
private static bool CompressionBenchmark(Stream inStream, Stream outStream, OutArchiveFormat format, CompressionMethod method, ref LibraryFeature? features, LibraryFeature testedFeature) { try { var compr = new SevenZipCompressor { ArchiveFormat = format, CompressionMethod = method }; compr.CompressStream(inStream, outStream); } catch (Exception) { return false; } features |= testedFeature; return true; }
/// <summary> /// Creates an archive from a folder /// </summary> /// <param name="pFolderToCompress">Folder to compress</param> /// <param name="pPassword">Password (optional)</param> /// <param name="pEncryptHeaders">Encrypt headers of the archive</param> /// <param name="pArchiveFormat">Format of the archive</param> /// <param name="pCompressionLevel">Level of compression</param> /// <param name="pCompressionMethod">Compression method</param> /// <returns>Result of the operation</returns> public bool ArchiveFolderX(string pFolderToCompress, string pPassword = null, bool pEncryptHeaders = false, OutArchiveFormat pArchiveFormat = OutArchiveFormat.Zip, CompressionLevel pCompressionLevel = CompressionLevel.Normal, CompressionMethod pCompressionMethod = CompressionMethod.Default ) { LastErrorText = null; if (string.IsNullOrEmpty(ArchiveName)) { LastErrorText = "CreateArchive(): Invalid archive specification"; return(false); } if (string.IsNullOrEmpty(pFolderToCompress = pFolderToCompress?.Trim()) || !Directory.Exists(pFolderToCompress)) { LastErrorText = "CreateArchive(): Invalid folder specification or folder not found"; return(false); } bool archiveOk = false; string backupFile = null; try { if (File.Exists(ArchiveName)) { backupFile = ArchiveName + ".bak"; File.Move(ArchiveName, backupFile); } SevenZipCompressor archiver = new SevenZipCompressor(); archiver.CompressionMode = CompressionMode.Create; archiver.ArchiveFormat = pArchiveFormat; archiver.CompressionLevel = pCompressionLevel; archiver.CompressionMethod = pCompressionMethod; if (!string.IsNullOrEmpty(pPassword = pPassword?.Trim())) { archiver.EncryptHeaders = pEncryptHeaders; archiver.CompressDirectory(pFolderToCompress, ArchiveName, true, pPassword); } else { archiver.CompressDirectory(pFolderToCompress, ArchiveName); } archiveOk = File.Exists(ArchiveName); } catch (Exception exception) { LastErrorText = $"CreateArchive(): {exception.Message}"; } finally { if (backupFile != null) { if (archiveOk) { File.Delete(backupFile); } else { File.Move(backupFile, ArchiveName); } } } return(archiveOk); }
/// <summary> /// Gets IOutArchive interface to pack 7-zip archives. /// </summary> /// <param name="format">Archive format.</param> /// <param name="user">Archive format user.</param> public static IOutArchive OutArchive(OutArchiveFormat format, object user) { lock (_syncRoot) { if (_outArchives[user][format] == null) { #if !WINCE && !MONO var sp = new SecurityPermission(SecurityPermissionFlag.UnmanagedCode); sp.Demand(); if (_modulePtr == IntPtr.Zero) { throw new SevenZipLibraryException(); } var createObject = (NativeMethods.CreateObjectDelegate) Marshal.GetDelegateForFunctionPointer( NativeMethods.GetProcAddress(_modulePtr, "CreateObject"), typeof(NativeMethods.CreateObjectDelegate)); if (createObject == null) { throw new SevenZipLibraryException(); } #endif object result; Guid interfaceId = #if !WINCE && !MONO typeof(IOutArchive).GUID; #else new Guid(((GuidAttribute)typeof(IOutArchive).GetCustomAttributes(typeof(GuidAttribute), false)[0]).Value); #endif Guid classID = Formats.OutFormatGuids[format]; try { #if !WINCE && !MONO createObject(ref classID, ref interfaceId, out result); #elif !MONO NativeMethods.CreateCOMObject(ref classID, ref interfaceId, out result); #else result = SevenZip.Mono.Factory.CreateInterface<IOutArchive>(classID, interfaceId, user); #endif } catch (Exception) { throw new SevenZipLibraryException("Your 7-zip library does not support this archive type."); } InitUserOutFormat(user, format); _outArchives[user][format] = result as IOutArchive; } return _outArchives[user][format]; #if !WINCE && !MONO } #endif }
/// <summary> /// 7z压缩 /// </summary> /// <param name="sourcePath">文件或者文件夹路径</param> /// <param name="destFileName">压缩后的文件路径</param> /// <param name="password">压缩密码</param> /// <param name="compressionMode">压缩模式</param> /// <param name="outArchiveFormat">压缩格式</param> /// <param name="compressionLevel">压缩级别</param> /// <param name="fileCompressionStarted">压缩开始事件</param> /// <param name="filesFound">文件发现事件</param> /// <param name="compressing">压缩进度事件</param> /// <param name="fileCompressionFinished">压缩完成事件</param> /// <returns>压缩结果</returns> public static bool CompressTo7z(string sourcePath, string destFileName, string password = null, CompressionMode compressionMode = CompressionMode.Create, OutArchiveFormat outArchiveFormat = OutArchiveFormat.SevenZip, CompressionLevel compressionLevel = CompressionLevel.High, EventHandler <FileNameEventArgs> fileCompressionStarted = null, EventHandler <IntEventArgs> filesFound = null, EventHandler <ProgressEventArgs> compressing = null, EventHandler <EventArgs> fileCompressionFinished = null) { var result = true; try { var tmp = new SevenZipCompressor { CompressionMode = compressionMode, ArchiveFormat = outArchiveFormat, CompressionLevel = compressionLevel }; if (fileCompressionStarted != null) { tmp.FileCompressionStarted += fileCompressionStarted; } if (filesFound != null) { tmp.FilesFound += filesFound; } if (compressing != null) { tmp.Compressing += compressing; } if (fileCompressionFinished != null) { tmp.FileCompressionFinished += fileCompressionFinished; } if (Directory.Exists(sourcePath)) { if (!string.IsNullOrEmpty(password)) { tmp.CompressDirectory(sourcePath, destFileName, password); } else { tmp.CompressDirectory(sourcePath, destFileName); } } else { result = false; } if (File.Exists(sourcePath)) { if (!string.IsNullOrEmpty(password)) { tmp.CompressFilesEncrypted(destFileName, password, sourcePath); } else { tmp.CompressFiles(destFileName, sourcePath); } } else { result = false; } } catch (Exception ex) { result = false; LogHelper.Error(ex, "7z压缩文件异常"); } return(result); }
public CreateArchive(IList <string> fileAndDirectoryFullPaths, bool compress, string archivePath, OutArchiveFormat defaultFormat = OutArchiveFormat.SevenZip, bool only = true) { InitializeComponent(); _fileAndDirectoryFullPaths = fileAndDirectoryFullPaths; txt_archivePath.Text = archivePath; if (compress) { rbtn_extract.Enabled = only; } else { rbtn_compress.Enabled = only; } rbtn_compress.Checked = compress; rbtn_extract.Checked = !compress; txt_archivename.Text = Path.GetFileNameWithoutExtension(fileAndDirectoryFullPaths.First().Split('\\').Last()); CreateGroepBoxEnum(typeof(OutArchiveFormat), gb_format); SetEnum(gb_format, defaultFormat.ToString()); CreateGroepBoxEnum(typeof(CompressionLevel), gb_compressionlevel); SetEnum(gb_compressionlevel, CompressionLevel.Normal.ToString()); }
/// <summary> /// Packing files for signature: /// `pack.files(object files, string output, enum format, enum method, integer level)` /// </summary> /// <param name="files">Input files.</param> /// <param name="name">Output archive.</param> /// <param name="type"></param> /// <param name="method"></param> /// <param name="rate"></param> /// <param name="pm"></param> /// <returns></returns> protected string stPackFiles(Argument[] files, string name, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { return(stPackFiles(files, name, null, type, method, rate, pm)); }
/// <summary> /// Packing files for signature: /// `pack.files(object files, string output, enum format, enum method, integer level)` /// </summary> /// <param name="files">Input files.</param> /// <param name="name">Output archive.</param> /// <param name="type"></param> /// <param name="method"></param> /// <param name="rate"></param> /// <param name="pm"></param> /// <returns></returns> protected string stPackFiles(Argument[] files, string name, OutArchiveFormat type, CompressionMethod method, CompressionLevel rate, IPM pm) { return stPackFiles(files, name, null, type, method, rate, pm); }