public override void Execute() { if (_cmdlet._directoryOrFilesFromPipeline == null) { _cmdlet._directoryOrFilesFromPipeline = new List<string> { _cmdlet.Path }; } var directoryOrFiles = _cmdlet._directoryOrFilesFromPipeline .Select(path => new FileInfo(System.IO.Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, path)).FullName).ToArray(); var archiveFileName = new FileInfo(System.IO.Path.Combine(_cmdlet.SessionState.Path.CurrentFileSystemLocation.Path, _cmdlet.ArchiveFileName)).FullName; switch (System.IO.Path.GetExtension(archiveFileName).ToLowerInvariant()) { case ".7z": _cmdlet.Format = OutArchiveFormat.SevenZip; break; case ".zip": _cmdlet.Format = OutArchiveFormat.Zip; break; case ".gz": _cmdlet.Format = OutArchiveFormat.GZip; break; case ".bz2": _cmdlet.Format = OutArchiveFormat.BZip2; break; case ".tar": _cmdlet.Format = OutArchiveFormat.Tar; break; case ".xz": _cmdlet.Format = OutArchiveFormat.XZ; break; } var compressor = new SevenZipCompressor { ArchiveFormat = _cmdlet.Format, CompressionLevel = _cmdlet.CompressionLevel, CompressionMethod = _cmdlet.CompressionMethod }; _cmdlet.CustomInitialization?.Invoke(compressor); var activity = directoryOrFiles.Length > 1 ? $"Compressing {directoryOrFiles.Length} Files to {archiveFileName}" : $"Compressing {directoryOrFiles.First()} to {archiveFileName}"; var currentStatus = "Compressing"; compressor.FilesFound += (sender, args) => Write($"{args.Value} files found for compression"); compressor.Compressing += (sender, args) => WriteProgress(new ProgressRecord(0, activity, currentStatus) { PercentComplete = args.PercentDone }); compressor.FileCompressionStarted += (sender, args) => { currentStatus = $"Compressing {args.FileName}"; Write($"Compressing {args.FileName}"); }; if (directoryOrFiles.Any(path => new FileInfo(path).Exists)) { var notFoundFiles = directoryOrFiles.Where(path => !new FileInfo(path).Exists).ToArray(); if (notFoundFiles.Any()) { throw new FileNotFoundException("File(s) not found: " + string.Join(", ", notFoundFiles)); } if (HasPassword) { compressor.CompressFiles(archiveFileName, directoryOrFiles); } else { compressor.CompressFilesEncrypted(archiveFileName, _cmdlet.Password, directoryOrFiles); } } if (directoryOrFiles.Any(path => new DirectoryInfo(path).Exists)) { if (directoryOrFiles.Length > 1) { throw new ArgumentException("Only one directory allowed as input"); } if (_cmdlet.Filter != null) { if (HasPassword) { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Password, _cmdlet.Filter, true); } else { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Filter, true); } } else { if (HasPassword) { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName, _cmdlet.Password); } else { compressor.CompressDirectory(directoryOrFiles[0], archiveFileName); } } } WriteProgress(new ProgressRecord(0, activity, "Finished") { RecordType = ProgressRecordType.Completed }); Write("Compression finished"); }
private void Compress() { //setup settings. try { _sevenZipCompressor = new SevenZipCompressor(tempPath); _sevenZipCompressor.ArchiveFormat = _format; _sevenZipCompressor.CompressionMethod = CompressionMethod.Default; _sevenZipCompressor.DirectoryStructure = true; _sevenZipCompressor.IncludeEmptyDirectories = true; _sevenZipCompressor.FastCompression = _fastcompression; _sevenZipCompressor.PreserveDirectoryRoot = false; _sevenZipCompressor.CompressionLevel = _compresstionlevel; _sevenZipCompressor.Compressing += Compressing; _sevenZipCompressor.FileCompressionStarted += FileCompressionStarted; _sevenZipCompressor.CompressionFinished += CompressionFinished; _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; try { if (_password != null) { for (int i = 0; i < _fileAndDirectoryFullPaths.Count; i++) { if (!Directory.Exists(_fileAndDirectoryFullPaths[i])) continue; //Compress directories var strings = _fileAndDirectoryFullPaths[i].Split('/'); if (_fileAndDirectoryFullPaths.Count == 1) { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format))); } else { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}_{3}.{2}", _archivePath, _archivename, SelectExtention(_format), _fileAndDirectoryFullPaths[i].Split('\\') .Last()), _password); } //remove the directorys from the list so they will not be compressed as files as wel _fileAndDirectoryFullPaths.Remove(_fileAndDirectoryFullPaths[i]); } //compress files if (_fileAndDirectoryFullPaths.Count > 0) { _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; _sevenZipCompressor.CompressFilesEncrypted( String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format)), _password, _fileAndDirectoryFullPaths.ToArray()); } } else { for (int i = 0; i < _fileAndDirectoryFullPaths.Count; i++) //var fullPath in _fileAndDirectoryFullPaths) { FileInfo fi = new FileInfo(_fileAndDirectoryFullPaths[i]); bytesoffiles += fi.Length; if (!Directory.Exists(_fileAndDirectoryFullPaths[i])) continue; //Compress directorys var strings = _fileAndDirectoryFullPaths[i].Split('/'); if (_fileAndDirectoryFullPaths.Count == 1) { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format))); } else { _sevenZipCompressor.CompressDirectory(_fileAndDirectoryFullPaths[i], String.Format("{0}/{1}_{3}.{2}", _archivePath, _archivename, SelectExtention(_format), _fileAndDirectoryFullPaths[i].Split('\\') .Last())); } //reset compression bar //FileCompressionFinished(null, null); //remove the directorys from the list so they will not be compressed as files as wel _fileAndDirectoryFullPaths.Remove(_fileAndDirectoryFullPaths[i]); } //compress files. if (_fileAndDirectoryFullPaths.Count > 0) { _sevenZipCompressor.FileCompressionFinished += FileCompressionFinished; _sevenZipCompressor.CompressFiles( String.Format("{0}/{1}.{2}", _archivePath, _archivename, SelectExtention(_format)), _fileAndDirectoryFullPaths.ToArray()); } } pb_totaalfiles.Invoke(new InvokeNone(() => { pb_totaalfiles.Value = 100; })); Done(); } catch (ThreadInterruptedException) { Dispose(true); } } catch { /* var dialog = new TaskDialog(); dialog.StandardButtons = TaskDialogStandardButtons.Ok; dialog.Text = ex.Message; dialog.Show(); */ } }
/// <summary> /// Compress files individually with .7z added on the end of the filename /// </summary> /// <param name="blShuttingDown"></param> private void compressFile(ref bool blShuttingDown) { SevenZip.SevenZipCompressor compressor = null; SevenZip.SevenZipExtractor extractor = null; Stream exreader = null; Stream creader = null; Stream extestreader = null; string[] strfilearr = new string[1]; try { AllFiles = Common.WalkDirectory(SourceFolder, ref blShuttingDown, FileNameFilter); SevenZip.SevenZipBase.SetLibraryPath(Get7ZipFolder()); if (SourceFolder != DestinationFolder) { Common.CreateDestinationFolders(SourceFolder, DestinationFolder); } if (blShuttingDown) { throw new Exception("Shutting Down"); } //Loop through every file foreach (System.IO.FileInfo file1 in AllFiles) { string str7File = Common.WindowsPathClean(file1.FullName + ".7z"); string strDestination = Common.WindowsPathCombine(DestinationFolder, str7File, SourceFolder); bool blArchiveOk = false; if (blShuttingDown) { _evt.WriteEntry("Compress: Shutting Down, about to Compress: " + file1.FullName, System.Diagnostics.EventLogEntryType.Information, 5130, 50); throw new Exception("Shutting Down"); } //Skip over already compressed files if (file1.Extension.ToLower() == ".7z" || file1.Extension.ToLower() == ".zip" || file1.Extension.ToLower() == ".rar") { continue; } if (Common.IsFileLocked(file1)) { _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5130, 50); continue; } if (!startCompressing(file1.LastWriteTime)) { continue; } try { if (File.Exists(strDestination)) { extestreader = new FileStream(strDestination, FileMode.Open); extractor = new SevenZipExtractor(extestreader); //If archive is not corrupted and KeepUncompressed is false then it is ok to delete the original if (extractor.Check() && KeepOriginalFile == false) { FileInfo file2 = new FileInfo(strDestination); //Same File compressed then ok to delete if (file1.LastWriteTime == file2.LastWriteTime && file1.Length == extractor.UnpackedSize && extractor.FilesCount == 1) { //File.SetAttributes(file1.FullName, FileAttributes.Normal); file1.IsReadOnly = false; File.Delete(file1.FullName); } file2 = null; } continue; } } catch (Exception) { _evt.WriteEntry("Compress: Failed to Delete Original File: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); continue; } finally { if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } } //If file already zipped and the last modified time are the same then delete //Compression of individual files strfilearr[0] = file1.FullName; try { compressor = new SevenZip.SevenZipCompressor(); compressor.CompressionMethod = SevenZip.CompressionMethod.Lzma2; compressor.CompressionLevel = CompressionLvl; compressor.ArchiveFormat = OutArchiveFormat.SevenZip; if (!string.IsNullOrEmpty(_encryptionPassword)) { compressor.ZipEncryptionMethod = ZipEncryptionMethod.Aes256; } long lFreeSpace = 0; lFreeSpace = Common.DriveFreeSpaceBytes(DestinationFolder); //Check for Enough Free Space to compress the file if (((file1.Length * 2) > lFreeSpace) && (lFreeSpace != -1)) { _evt.WriteEntry("Compress: Not enough available free space to compress this file: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5140, 50); compressor = null; continue; } if (lFreeSpace == -1) { _evt.WriteEntry("Compress: Only files local to this machine should be compressed. Performance problem can occur with large files over the network. " + file1.FullName, System.Diagnostics.EventLogEntryType.Warning, 5150, 50); } //Compress or Compress and Encrypt Files if (!string.IsNullOrEmpty(_encryptionPassword)) { creader = new FileStream(str7File, FileMode.OpenOrCreate); //Encrypt the file if password is specified AES256 aes = new AES256(ep); string upassword = aes.Decrypt(_encryptionPassword); compressor.CompressFilesEncrypted(creader, upassword, strfilearr); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7File, FileMode.Open); extractor = new SevenZipExtractor(exreader, upassword); upassword = ""; } else { if (Common.IsFileLocked(file1)) { _evt.WriteEntry("Compress: File is locked: " + file1.FullName, System.Diagnostics.EventLogEntryType.Error, 5070, 50); continue; } creader = new FileStream(str7File, FileMode.OpenOrCreate); compressor.CompressFiles(creader, strfilearr); creader.Close(); creader.Dispose(); creader = null; exreader = new FileStream(str7File, FileMode.Open); extractor = new SevenZipExtractor(exreader); } //7Zip file ok? blArchiveOk = extractor.Check(); exreader.Close(); exreader.Dispose(); exreader = null; verifyArchive(blArchiveOk, str7File, file1.FullName); } catch (Exception ex) { _evt.WriteEntry("Compress: " + ex.Message.ToString(), System.Diagnostics.EventLogEntryType.Error, 5000, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } compressor = null; } }// end foreach _evt.WriteEntry("Compress: Complete Files Compressed: " + FilesCompressed.Count, System.Diagnostics.EventLogEntryType.Information, 5000, 50); } catch (Exception ex) { _evt.WriteEntry("Compress: Compress Files Attempt Failed" + ex.Message, System.Diagnostics.EventLogEntryType.Error, 5170, 50); } finally { if (creader != null) { creader.Close(); creader.Dispose(); creader = null; } if (exreader != null) { exreader.Close(); exreader.Dispose(); exreader = null; } if (extractor != null) { extractor.Dispose(); extractor = null; } if (extestreader != null) { extestreader.Close(); extestreader.Dispose(); extestreader = null; } compressor = null; } }