### Installation Wizard SFX Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Example of creating an SFX with an installation wizard module. ```csharp var sfx = new SharpSevenZipSfx(SfxModule.Installer); sfx.CreateArchive(@"C:\ProgramFiles", @"C:\Install_Program.exe"); ``` -------------------------------- ### Custom Library Path Configuration Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example showing how to configure an alternative 7-Zip installation path. ```csharp // Configure alternative 7-Zip installation SharpSevenZipLibraryManager.SetLibraryPath(@"D:\7Zip\7z.dll"); var extractor = new SharpSevenZipExtractor("archive.7z"); ``` -------------------------------- ### Standard Extraction Setup Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Basic example of extracting an archive using the default library location. ```csharp // Basic extraction with library in default location var extractor = new SharpSevenZipExtractor("archive.7z"); extractor.ExtractArchive(@"C:\Output"); ``` -------------------------------- ### Show command example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/gpl.txt Example of a command to display license details. ```bash show c ``` -------------------------------- ### Example: Maximum LZMA Compression Configuration Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example demonstrating how to configure LZMA compression for maximum compression settings. ```csharp // Configure for maximum compression SharpSevenZipCompressor.LzmaDictionarySize = 32 * 1024 * 1024; // 32 MB SharpSevenZipCompressor.LzmaNumFastBytes = 273; // Maximum using (var stream = new LzmaEncodeStream(output, 32 * 1024 * 1024)) { input.CopyTo(stream); } ``` -------------------------------- ### FileInfoEventArgs Usage Example (Extraction Started) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example of how to handle the FileExtractionStarted event to log the file being extracted. ```csharp extractor.FileExtractionStarted += (s, e) => { Console.WriteLine($"Extracting: {e.FileInfo.FileName}"); }; ``` -------------------------------- ### Initialize extractor from a file path with automatic format detection. Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md This example demonstrates initializing the SharpSevenZipExtractor with a file path and then extracting its contents. It also shows how to get the number of files within the archive. ```csharp using (var extractor = new SharpSevenZipExtractor(@"C:\Archive.7z")) { var fileCount = extractor.FilesCount; extractor.ExtractArchive(@"C:\Output"); } ``` -------------------------------- ### Constructor with SfxModule Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Initializes SharpSevenZipSfx with a specific SFX module type. ```csharp var sfx = new SharpSevenZipSfx(SfxModule.Installer); ``` -------------------------------- ### Interactive Mode Notice Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/gpl.txt Example of a short notice to display when a program starts in interactive mode. ```text Copyright (C) This program comes with ABSOLUTELY NO WARRANTY; for details type `show w'. ``` -------------------------------- ### LzmaException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example demonstrating how to catch and handle LzmaException during LZMA decompression. ```csharp try { using (var input = File.OpenRead("data.lzma")) using (var decoder = new LzmaDecodeStream(input)) using (var output = File.Create("output.bin")) { decoder.CopyTo(output); } } catch (LzmaException ex) { Console.WriteLine($"LZMA decompression failed: {ex.Message}"); } ``` -------------------------------- ### Flush() Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to flush buffered data to the output stream before reading final compressed data. ```csharp encoder.Write(data, 0, data.Length); encoder.Flush(); // Output stream now contains all compressed data ``` -------------------------------- ### ExtractArchive Method Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Example of using the ExtractArchive() method to extract files to a directory. ```csharp extractor.ExtractArchive(@"C:\Output"); ``` -------------------------------- ### Default Constructor Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Initializes SharpSevenZipSfx with the default SFX module for the current platform. ```csharp var sfx = new SharpSevenZipSfx(); ``` -------------------------------- ### Catch-all Base Exception Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example of catching the base SharpSevenZipException. ```csharp try { var extractor = new SharpSevenZipExtractor("archive.7z"); } catch (SharpSevenZipException ex) { Console.WriteLine($"SharpSevenZip error: {ex.Message}"); } ``` -------------------------------- ### Read() Method Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to read and decompress data from the input stream into a buffer. ```csharp byte[] buffer = new byte[4096]; int bytesRead = decoder.Read(buffer, 0, buffer.Length); ``` -------------------------------- ### Constructor with Custom Module File Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Initializes SharpSevenZipSfx with a custom SFX module file path. ```csharp var sfx = new SharpSevenZipSfx(@"C:\custom_sfx.exe"); ``` -------------------------------- ### ArchiveFileInfo Usage Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/types.md Example of how to iterate through ArchiveFileInfo. ```csharp var extractor = new SharpSevenZipExtractor("archive.7z"); foreach (var file in extractor.ArchiveFileData) { Console.WriteLine($"File: {file.FileName}"); Console.WriteLine($" Size: {file.Size} bytes"); Console.WriteLine($" Encrypted: {file.Encrypted}"); Console.WriteLine($" Method: {file.Method}"); } ``` -------------------------------- ### SharpSevenZipLibraryException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example of catching SharpSevenZipLibraryException, which is thrown when the native 7-zip library cannot be loaded or used. ```csharp try { var extractor = new SharpSevenZipExtractor("archive.7z"); } catch (SharpSevenZipLibraryException ex) { Console.WriteLine("Failed to load 7-zip library:"); Console.WriteLine($" {ex.Message}"); Console.WriteLine(" Ensure 7z.dll is installed and in the correct path."); } ``` -------------------------------- ### EventSynchronization Usage Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example of setting the EventSynchronization property. ```csharp var extractor = new SharpSevenZipExtractor("archive.7z"); extractor.EventSynchronization = EventSynchronizationStrategy.AlwaysSynchronous; // Now all events fire synchronously on the calling thread ``` -------------------------------- ### ArchiveFileData Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Example of iterating through ArchiveFileData to display file names and sizes. ```csharp foreach (var file in extractor.ArchiveFileData) { Console.WriteLine($"{file.FileName}: {file.Size} bytes"); } ``` -------------------------------- ### ExtractFileCallback Implementation Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example implementation of the ExtractFileCallback delegate. ```csharp void ProcessFile(ExtractFileCallbackArgs args) { if (args.Reason == ExtractFileCallbackReason.Begin) { // Decide where to extract } else if (args.Reason == ExtractFileCallbackReason.Done) { // Extraction succeeded } else if (args.Reason == ExtractFileCallbackReason.Failure) { // Extraction failed } } ``` -------------------------------- ### Check Method Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Example of using the Check() method to verify archive integrity. ```csharp if (extractor.Check()) { Console.WriteLine("Archive is valid"); } else { Console.WriteLine("Archive is corrupted"); } ``` -------------------------------- ### SharpSevenZipInvalidFileNamesException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example demonstrating how to catch and handle SharpSevenZipInvalidFileNamesException during archive extraction. ```csharp try { extractor.ExtractArchive(@"C:\Output"); } catch (SharpSevenZipInvalidFileNamesException ex) { Console.WriteLine($"Archive contains invalid file names: {ex.Message}"); } ``` -------------------------------- ### Basic SFX Creation Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Example of basic SFX creation from a directory. ```csharp var sfx = new SharpSevenZipSfx(); sfx.CreateArchive(@"C:\MyApplication", @"C:\MyApp_Setup.exe"); ``` -------------------------------- ### Compress File Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to compress a file using LzmaEncodeStream. ```csharp string inputFile = "largefile.bin"; string outputFile = "largefile.bin.lzma"; using (var outputStream = File.Create(outputFile)) using (var encoder = new LzmaEncodeStream(outputStream, 16 * 1024 * 1024)) using (var inputStream = File.OpenRead(inputFile)) { inputStream.CopyTo(encoder); encoder.Flush(); } ``` -------------------------------- ### ArgumentException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example showing how to catch and handle ArgumentException for invalid stream parameters or file paths. ```csharp try { var extractor = new SharpSevenZipExtractor(invalidStream); } catch (ArgumentException ex) { Console.WriteLine($"Invalid argument: {ex.ParamName} - {ex.Message}"); } ``` -------------------------------- ### Compress with Custom LZMA Parameters Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to configure LZMA parameters for maximum compression and then compress a file. ```csharp // Configure LZMA for maximum compression SharpSevenZipCompressor.LzmaDictionarySize = 32 * 1024 * 1024; // 32 MB dictionary SharpSevenZipCompressor.LzmaNumFastBytes = 273; // Maximum SharpSevenZipCompressor.LzmaMatchFinder = "bt4"; using (var input = File.OpenRead("input.bin")) using (var output = File.Create("output.lzma")) { var encoder = new LzmaEncodeStream(output, 32 * 1024 * 1024); input.CopyTo(encoder); encoder.Flush(); } ``` -------------------------------- ### Multi-Volume Archive Creation Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example for creating a multi-volume archive with a specified volume size and compression level. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.SevenZip; compressor.VolumeSize = 700 * 1024 * 1024; // 700 MB per volume compressor.CompressionLevel = CompressionLevel.Ultra; compressor.CompressDirectory(@"C:\LargeFolder", @"C:\Archive.7z"); // Creates Archive.7z, Archive.7z.001, Archive.7z.002, etc. ``` -------------------------------- ### Event-Driven Extraction Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example demonstrating event-driven extraction with progress updates and custom event handling. ```csharp var extractor = new SharpSevenZipExtractor("archive.7z"); extractor.EventSynchronization = EventSynchronizationStrategy.AlwaysSynchronous; extractor.Extracting += (s, e) => progressBar.Value = (int)e.PercentDone; extractor.FileExtractionStarted += (s, e) => statusLabel.Text = $"Extracting {e.FileInfo.FileName}..." ; extractor.FileExists += (s, e) => e.Cancel = true; // Skip existing files try { extractor.ExtractArchive(@"C:\Output"); } catch (SharpSevenZipException ex) { MessageBox.Show($"Error: {ex.Message}"); } ``` -------------------------------- ### CompressionMode Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Demonstrates setting the compression mode to either create a new archive or update an existing one. ```csharp compressor.CompressionMode = CompressionMode.Update; ``` -------------------------------- ### SharpSevenZipSfxValidationException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example showing how to catch and handle SharpSevenZipSfxValidationException when configuring a self-extracting archive. ```csharp try { var sfx = new SharpSevenZipSfx(SfxModule.Custom); sfx.ModuleFileName = "nonexistent.sfx"; } catch (SharpSevenZipSfxValidationException ex) { Console.WriteLine($"SFX validation error: {ex.Message}"); } ``` -------------------------------- ### SharpSevenZipCompressionFailedException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example of catching SharpSevenZipCompressionFailedException, which is thrown when a compression operation fails. ```csharp try { compressor.CompressDirectory(@"C:\Source", @"C:\Archive.7z"); } catch (SharpSevenZipCompressionFailedException ex) { Console.WriteLine($"Compression failed: {ex.Message}"); // Check disk space, temporary path permissions } ``` -------------------------------- ### Basic Compression with Level Control Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Example demonstrating basic compression with control over the compression level. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.SevenZip; compressor.CompressionLevel = CompressionLevel.High; compressor.CompressDirectory(@"C:\SourceFolder", @"C:\archive.7z"); ``` -------------------------------- ### SharpSevenZipArchiveException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example of catching SharpSevenZipArchiveException, which is thrown when the archive structure is invalid or cannot be read. ```csharp try { var extractor = new SharpSevenZipExtractor("archive.zip"); } catch (SharpSevenZipArchiveException ex) { Console.WriteLine($"Archive is corrupted: {ex.Message}"); } ``` -------------------------------- ### Decompress File Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to decompress a file using LzmaDecodeStream. ```csharp string compressedFile = "data.lzma"; string outputFile = "data.bin"; using (var input = File.OpenRead(compressedFile)) using (var decoder = new LzmaDecodeStream(input)) using (var output = File.Create(outputFile)) { decoder.CopyTo(output); } ``` -------------------------------- ### CompressionMethod Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Illustrates setting the compression method. Different methods are available depending on the archive format, such as LZMA2 for 7-zip or Deflate for Zip. ```csharp compressor.CompressionMethod = CompressionMethod.Lzma2; ``` -------------------------------- ### Custom Module SFX Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Example of creating an SFX using a custom SFX module. ```csharp var sfx = new SharpSevenZipSfx(@"C:\Path\To\CustomModule.sfx"); if (sfx.SfxModule == SfxModule.Custom) { Console.WriteLine("Using custom SFX module"); } sfx.CreateArchive(@"C:\Files", @"C:\custom_installer.exe"); ``` -------------------------------- ### FileOverwriteEventArgs Usage Example (Prompt User) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example showing how to prompt the user to decide whether to overwrite an existing file. ```csharp extractor.FileExists += (s, e) => { if (MessageBox.Show($"Overwrite {e.FileName}?", "File Exists", MessageBoxButtons.YesNo) == DialogResult.Yes) { e.Cancel = false; // Overwrite } else { e.Cancel = true; // Skip } }; ``` -------------------------------- ### ProgressEventArgs Usage Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example of how to subscribe to the Extracting event and update UI elements based on progress. ```csharp extractor.Extracting += (s, e) => { progressBar.Value = (int)e.PercentDone; statusLabel.Text = $"Progress: {e.PercentDone:F1}%"; }; ``` -------------------------------- ### CompressionLevel Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Shows how to set the compression level, ranging from None to Ultra, to control the trade-off between compression speed and archive size. ```csharp compressor.CompressionLevel = CompressionLevel.Ultra; ``` -------------------------------- ### LzmaDecodeStream Constructor Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example demonstrating how to initialize LzmaDecodeStream to decompress data from an input stream. ```csharp using (var input = File.OpenRead("data.lzma")) { using (var decoder = new LzmaDecodeStream(input)) using (var output = File.Create("data.bin")) { decoder.CopyTo(output); } } ``` -------------------------------- ### Complete Example: Extraction with Progress and Conflict Handling Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md This C# code demonstrates how to use the SharpSevenZipExtractor class to extract an archive, providing progress updates, handling file extraction events, resolving conflicts, and managing exceptions. ```csharp var extractor = new SharpSevenZipExtractor("archive.7z"); // Progress reporting extractor.Extracting += (s, e) => { Console.WriteLine($"Progress: {e.PercentDone:F1}% ({e.BytesDone}/{extractor.UnpackedSize} bytes)"); }; // File tracking extractor.FileExtractionStarted += (s, e) => { Console.WriteLine($" Extracting: {e.FileInfo.FileName}..."); }; extractor.FileExtractionFinished += (s, e) => { Console.WriteLine($" ✓ {e.FileInfo.FileName}"); }; // Conflict resolution extractor.FileExists += (s, e) => { Console.WriteLine($" File exists: {e.FileName}"); Console.Write(" [O]verwrite, [S]kip, [R]ename? "); var response = Console.ReadLine()?.ToUpper(); switch (response) { case "O": e.Cancel = false; break; case "S": e.Cancel = true; break; case "R": Console.Write(" New name: "); e.FileName = Console.ReadLine(); break; default: e.Cancel = true; break; } }; // Completion extractor.ExtractionFinished += (s, e) => { Console.WriteLine("Extraction complete!"); }; try { extractor.ExtractArchive(@"C:\Output"); } catch (SharpSevenZipExtractionFailedException ex) { Console.WriteLine($"Extraction failed: {ex.Message}"); } finally { extractor.Dispose(); } ``` -------------------------------- ### VolumeSize Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Shows how to set the volume size in bytes for creating multi-volume archives, specifically for the 7-zip format. ```csharp compressor.VolumeSize = 100 * 1024 * 1024; // 100 MB volumes ``` -------------------------------- ### Password-Protected Archives Creation Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example for creating an encrypted archive with a specified password and compression level. ```csharp // Create encrypted archive var compressor = new SharpSevenZipCompressor(); compressor.Password = "SecurePassword"; compressor.CompressionLevel = CompressionLevel.High; compressor.CompressDirectory(@"C:\SourceDir", @"C:\Archive.7z"); ``` -------------------------------- ### ZIP Archive with AES Encryption Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example for creating a ZIP archive with AES-256 encryption and a password. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.Zip; compressor.ZipEncryptionMethod = ZipEncryptionMethod.AES256; compressor.Password = "StrongPassword"; compressor.CompressionLevel = CompressionLevel.High; compressor.CompressFiles(@"C:\Secure.zip", @"C:\File1.txt", @"C:\File2.doc"); ``` -------------------------------- ### FileOverwriteEventArgs Usage Example (Auto-Rename) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example demonstrating how to automatically rename an existing file to avoid overwriting. ```csharp extractor.FileExists += (s, e) => { var dir = Path.GetDirectoryName(e.FileName); var nameOnly = Path.GetFileNameWithoutExtension(e.FileName); var ext = Path.GetExtension(e.FileName); e.FileName = Path.Combine(dir, $"{nameOnly}_new{ext}"); }; ``` -------------------------------- ### FileExists Event Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Example of handling the FileExists event to skip existing files during extraction. ```csharp extractor.FileExists += (s, e) => { e.Cancel = true; // Skip existing files }; ``` -------------------------------- ### FileOverwriteEventArgs Usage Example (Skip Existing) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example demonstrating how to set Cancel to true to skip overwriting an existing file. ```csharp extractor.FileExists += (s, e) => { e.Cancel = true; // Skip the file }; ``` -------------------------------- ### TargetPlatform Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Sets the target platform for SFX module selection and then initializes SharpSevenZipSfx. ```csharp SharpSevenZipSfx.TargetPlatform = SfxTarget.X64; var sfx = new SharpSevenZipSfx(); ``` -------------------------------- ### ExtractFileCallbackArgs Usage Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example demonstrating how to use the ExtractFiles method with a callback to control extraction targets. ```csharp extractor.ExtractFiles(args => { if (args.FileInfo.FileName.EndsWith(".txt")) { args.ExtractToFile = Path.Combine(@"C:\Output", args.FileInfo.FileName); } else if (args.FileInfo.FileName.EndsWith(".pdf")) { using (var file = File.Create($@"C:\PDFs\{args.FileInfo.FileName}")) { args.ExtractToStream = file; } } else { args.CancelExtraction = true; // Skip others } }); ``` -------------------------------- ### Custom Parameters for Compression Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/README.md This example demonstrates how to set custom compression switches for SharpSevenZipCompressor, compatible with 7z.exe command-line switches. It specifically shows how to enable multi-threaded compression. ```csharp SharpSevenZipCompressor.CustomParameters.Add("mt", "on"); ``` -------------------------------- ### Password-Protected Archive Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Example showing how to create a password-protected archive. ```csharp // Inherit from SharpSevenZipCompressor to set password, or use directly var compressor = new SharpSevenZipCompressor(); compressor.Password = "MyPassword"; // Set via base class property compressor.ArchiveFormat = OutArchiveFormat.SevenZip; compressor.CompressFiles(@"C:\archive.7z", @"C:\file1.txt", @"C:\file2.doc"); ``` -------------------------------- ### ModuleFileName Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Demonstrates setting the custom SFX module file name and checking the detected SfxModule. ```csharp sfx.ModuleFileName = @"C:\MyModule.sfx"; if (sfx.SfxModule == SfxModule.Extended) { Console.WriteLine("Detected extended SFX module"); } ``` -------------------------------- ### Maximum Compression 7-Zip Archive Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example for creating a 7-Zip archive with maximum compression settings, including multi-threading and custom parameters. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.SevenZip; compressor.CompressionLevel = CompressionLevel.Ultra; compressor.CompressionMethod = CompressionMethod.Lzma2; compressor.CustomParameters.Add("mt", "on"); // Multi-thread compressor.CustomParameters.Add("d", "256m"); // 256 MB dictionary compressor.CustomParameters.Add("mfbt", "bt4"); // Binary tree matcher compressor.CompressDirectory(@"C:\Data", @"C:\Archive.7z"); ``` -------------------------------- ### Platform-Specific SFX Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Example of creating both 32-bit and 64-bit SFX versions. ```csharp // Create 32-bit version SharpSevenZipSfx.TargetPlatform = SfxTarget.X86; var sfx32 = new SharpSevenZipSfx(); sfx32.CreateArchive(@"C:\App", @"C:\App_x86.exe"); // Create 64-bit version SharpSevenZipSfx.TargetPlatform = SfxTarget.X64; var sfx64 = new SharpSevenZipSfx(); sfx64.CreateArchive(@"C:\App", @"C:\App_x64.exe"); ``` -------------------------------- ### Multiple Files SFX Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Example of creating an SFX containing multiple specified files. ```csharp var sfx = new SharpSevenZipSfx(SfxModule.Default); var files = new[] { @"C:\README.txt", @"C:\LICENSE.txt", @"C:\app.exe", @"C:\config.xml" }; sfx.CreateArchive(files, @"C:\application.exe"); ``` -------------------------------- ### ArchiveFormat Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Demonstrates how to set the output archive format for the compressor. Supported formats include SevenZip, Zip, GZip, BZip2, Tar, XZ, and Wim. ```csharp compressor.ArchiveFormat = OutArchiveFormat.Zip; ``` -------------------------------- ### Use App Configuration Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Shows how to store the library path in application configuration (appsettings.json) and load it during startup. ```json // appsettings.json { "SharpSevenZip": { "LibraryPath": "C:\\Program Files\\7-Zip\\7z.dll" } } // Startup var config = new ConfigurationBuilder() .AddJsonFile("appsettings.json") .Build(); var libPath = config["SharpSevenZip:LibraryPath"]; SharpSevenZipLibraryManager.SetLibraryPath(libPath); ``` -------------------------------- ### Configure Library Path Once Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates the best practice of setting the 7z.dll library path once during application startup. ```csharp // In Program.Main or Application startup public static void Main(string[] args) { // Configure once before any SharpSevenZip operations SharpSevenZipLibraryManager.SetLibraryPath(@"C:\7Zip\7z.dll"); // Rest of application... RunApplication(); } ``` -------------------------------- ### Performance Optimization: Compression Levels Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Illustrates how to choose appropriate compression levels to balance compression ratio, CPU usage, and time. ```csharp var compressor = new SharpSevenZipCompressor(); // Quick backup of active files compressor.CompressionLevel = CompressionLevel.Fast; compressor.CompressDirectory(@"C:\Active", @"C:\Backup_Fast.7z"); // Important archive, time not critical compressor.CompressionLevel = CompressionLevel.Ultra; compressor.CompressDirectory(@"C:\Important", @"C:\Archive_Max.7z"); // General purpose compressor.CompressionLevel = CompressionLevel.Normal; compressor.CompressDirectory(@"C:\Data", @"C:\Archive.7z"); ``` -------------------------------- ### CustomParameters Property Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Demonstrates adding custom parameters to the compressor, similar to 7z.exe command-line switches, for advanced configuration like enabling multi-threading. ```csharp compressor.CustomParameters.Add("mt", "on"); // Enable multi-threading compressor.CustomParameters.Add("d", "32"); // Dictionary size ``` -------------------------------- ### Log Archive Operations Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Example of logging information during archive extraction using a logger instance. ```csharp logger.Info($"Extracting archive: {archiveFile}"); logger.Debug($"Archive format: {extractor.Format}"); logger.Debug($"Files: {extractor.FilesCount}, Size: {extractor.UnpackedSize} bytes"); logger.Debug($"Solid: {extractor.IsSolid}"); try { extractor.ExtractArchive(outputDir); logger.Info("Extraction completed successfully"); } catch (SharpSevenZipException ex) { logger.Error($"Extraction failed: {ex.Message}", ex); throw; } ``` -------------------------------- ### ObjectDisposedException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example illustrating when an ObjectDisposedException is thrown after disposing an extractor instance. ```csharp var extractor = new SharpSevenZipExtractor("archive.7z"); extractor.Dispose(); // Next call throws ObjectDisposedException: extractor.ExtractArchive(@"C:\Output"); // Error! ``` -------------------------------- ### LzmaEncodeStream() Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Initializes an LzmaEncodeStream with default buffer capacity and internal memory output, then copies data from an input file to the encoder. ```csharp using (var encoder = new LzmaEncodeStream()) { using (var file = File.OpenRead("input.txt")) { file.CopyTo(encoder); encoder.Flush(); byte[] compressed = encoder.GetBuffer(); // Not accessible; use via stream } } ``` -------------------------------- ### How to Apply These Terms to Your New Programs Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/gpl.txt Instructions on how to apply the GNU GPL to new programs, including copyright notices and warranty disclaimers. ```text Copyright (C) This program is free software: you can redistribute it and/or modify it under the terms of the GNU General Public License as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version. This program is distributed in the hope that it will be useful, but WITHOUT ANY WARRANTY; without even the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU General Public License for more details. You should have received a copy of the GNU General Public License along with this program. If not, see . ``` -------------------------------- ### Accurate Progress Tracking Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates how to implement accurate progress tracking by using `PercentDelta` and reporting progress at specific intervals (e.g., every 5%). ```csharp int lastReportedPercent = 0; extractor.Extracting += (s, e) => { // Report at 5% intervals int currentPercent = (int)e.PercentDone; if (currentPercent >= lastReportedPercent + 5) { Console.WriteLine($"{currentPercent}% complete"); lastReportedPercent = currentPercent; } }; extractor.ExtractArchive(@"C:\Output"); ``` -------------------------------- ### SharpSevenZipExtractionFailedException Example Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/exceptions.md Example of catching SharpSevenZipExtractionFailedException, which is thrown when an extraction operation fails. ```csharp try { extractor.ExtractArchive(@"C:\Output"); } catch (SharpSevenZipExtractionFailedException ex) { Console.WriteLine($"Extraction failed: {ex.Message}"); // May contain details about which file failed } ``` -------------------------------- ### Initialize extractor from a stream with automatic format detection and default disposal behavior. Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md This example shows how to initialize the SharpSevenZipExtractor using a FileStream, allowing for extraction of archive data directly from a stream. The `leaveOpen` parameter is set to `false` by default, meaning the stream will be closed when the extractor is disposed. ```csharp using (var fileStream = new FileStream(@"C:\Archive.zip", FileMode.Open, FileAccess.Read)) using (var extractor = new SharpSevenZipExtractor(fileStream, leaveOpen: false)) { extractor.ExtractArchive(@"C:\Output"); } ``` -------------------------------- ### ExtractBytes Example Usage Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/lzma-streams.md Example of using ExtractBytes to decompress a file. ```csharp byte[] compressed = File.ReadAllBytes("data.lzma"); byte[] decompressed = SharpSevenZipExtractor.ExtractBytes(compressed); File.WriteAllBytes("data.bin", decompressed); ``` -------------------------------- ### Use Appropriate Compression Methods Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates how to select different compression methods (PPMd, LZMA2, Deflate) based on the type of data being compressed (text documents, general binary data, compatibility with ZIP readers). ```csharp var compressor = new SharpSevenZipCompressor(); compressor.ArchiveFormat = OutArchiveFormat.SevenZip; // Text documents: PPMd is excellent compressor.CompressionMethod = CompressionMethod.Ppmd; compressor.CustomParameters.Add("mem", "256m"); compressor.CompressFiles(@"C:\docs.7z", @"C:\readme.txt", @"C:\manual.txt"); // General binary data: LZMA2 with multithreading compressor.CompressionMethod = CompressionMethod.Lzma2; compressor.CustomParameters.Add("mt", "on"); compressor.CompressDirectory(@"C:\Data", @"C:\data.7z"); // Compatibility with ZIP readers: Deflate compressor.ArchiveFormat = OutArchiveFormat.Zip; compressor.CompressionMethod = CompressionMethod.Deflate; compressor.CompressFiles(@"C:\portable.zip", @"C:\file1.txt"); ``` -------------------------------- ### Provide Fallback Locations Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Illustrates how to configure fallback locations for the 7z.dll to ensure the library can be found. ```csharp private static void ConfigureLibrary() { var paths = new[] { @"C:\Custom7Zip\7z.dll", @"C:\Program Files\7-Zip\7z.dll", @"C:\Program Files (x86)\7-Zip\7z.dll", Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "x64", "7z.dll") }; foreach (var path in paths) { if (File.Exists(path)) { SharpSevenZipLibraryManager.SetLibraryPath(path); return; } } throw new FileNotFoundException("7z.dll not found in any expected location"); } ``` -------------------------------- ### Incremental Backups Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Explains how to perform incremental backups by using the update mode to add new files to an existing archive. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.CompressionMode = CompressionMode.Update; // First backup compressor.CompressDirectory(@"C:\InitialData", @"C:\backup.7z"); // Later, add new files compressor.CompressionMode = CompressionMode.Update; compressor.CompressFiles(@"C:\backup.7z", @"C:\NewFile.txt"); ``` -------------------------------- ### Resource Management: Using Statements Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates the correct and incorrect usage of 'using' statements for SharpSevenZipExtractor to prevent resource leaks. ```csharp // ✓ Correct using (var extractor = new SharpSevenZipExtractor("archive.7z")) { extractor.ExtractArchive(@"C:\Output"); } // ✗ Avoid var extractor = new SharpSevenZipExtractor("archive.7z"); extractor.ExtractArchive(@"C:\Output"); // Resource leak! Library stays loaded, handles not released ``` -------------------------------- ### Pre-allocate Space for Large Archives Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Illustrates how to check for sufficient disk space before extracting large archives to prevent errors and improve performance. ```csharp var outputDir = @"C:\Output"; var driveInfo = new DriveInfo(outputDir); using (var extractor = new SharpSevenZipExtractor("large.7z")) { // Ensure sufficient disk space if (driveInfo.AvailableFreeSpace < extractor.UnpackedSize) throw new InvalidOperationException("Insufficient disk space"); extractor.ExtractArchive(outputDir); } ``` -------------------------------- ### CustomParameters Dictionary Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Advanced 7z.exe-compatible command-line parameters. ```csharp public Dictionary CustomParameters { get; } ``` ```csharp compressor.CustomParameters.Add("mt", "on"); // Multi-threading compressor.CustomParameters.Add("d", "32"); // Dictionary size (MB) compressor.CustomParameters.Add("mfbt", "bt4"); // Match finder type compressor.CustomParameters.Add("mem", "256m"); // PPMd memory (PPMd only) ``` -------------------------------- ### FileInfoEventArgs Usage Example (Extraction Finished) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/events-and-callbacks.md Example of how to handle the FileExtractionFinished event to log the completion of file extraction. ```csharp extractor.FileExtractionFinished += (s, e) => { Console.WriteLine($"Completed: {e.FileInfo.FileName}"); }; ``` -------------------------------- ### Skip Existing Files Safely Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates how to handle existing files during extraction by subscribing to the `FileExists` event and setting `e.Cancel = true` to skip the file and add it to a list of skipped files. ```csharp var skippedFiles = new List(); extractor.FileExists += (s, e) => { e.Cancel = true; skippedFiles.Add(e.FileName); }; extractor.ExtractArchive(@"C:\Output"); if (skippedFiles.Count > 0) logger.Info($"Skipped {skippedFiles.Count} existing files"); ``` -------------------------------- ### UniqueID Property Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Gets a unique identifier for this instance (read-only). ```csharp public int UniqueID { get; } ``` -------------------------------- ### ArchiveFileNames Property Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Gets a list of all file names in the archive. ```csharp public ReadOnlyCollection ArchiveFileNames { get; } ``` -------------------------------- ### FilesCount Property Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Gets the number of files and directories in the archive. ```csharp public uint FilesCount { get; } ``` -------------------------------- ### Resource Management: Handling Streams Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Illustrates how to manage stream disposal when passing streams to SharpSevenZipExtractor using the 'leaveOpen' parameter. ```csharp // Stream closed after disposal using (var fileStream = File.OpenRead("archive.7z")) using (var extractor = new SharpSevenZipExtractor(fileStream, leaveOpen: false)) { extractor.ExtractArchive(@"C:\Output"); // fileStream automatically disposed } // Stream remains open after disposal using (var memoryStream = new MemoryStream(archiveData)) using (var extractor = new SharpSevenZipExtractor(memoryStream, leaveOpen: true)) { extractor.ExtractArchive(@"C:\Output"); // memoryStream remains open; you dispose it } ``` -------------------------------- ### Password-Protected Archives Extraction Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Example for extracting an encrypted archive using a password. ```csharp // Extract encrypted archive var extractor = new SharpSevenZipExtractor("encrypted.7z", "MyPassword"); extractor.ExtractArchive(@"C:\Output"); ``` -------------------------------- ### UserExceptions Collection Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Gets exceptions thrown from event handlers when ReportErrors is false. ```csharp public ReadOnlyCollection UserExceptions { get; } ``` -------------------------------- ### Compress Directory Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/INDEX.md Quick start pattern for compressing a directory. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.CompressionLevel = CompressionLevel.High; compressor.CompressDirectory(@"C:\Source", @"C:\Archive.7z"); ``` -------------------------------- ### Extract Archive Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/INDEX.md Quick start pattern for extracting an archive. ```csharp using (var extractor = new SharpSevenZipExtractor(@"C:\Archive.7z")) { extractor.ExtractArchive(@"C:\Output"); } ``` -------------------------------- ### SetLibraryPath Method (string) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Configures the full path to the 7-zip native library DLL. ```csharp public static void SetLibraryPath(string libraryPath) ``` ```csharp SharpSevenZipLibraryManager.SetLibraryPath(@"C:\Custom7Zip\7z.dll"); var extractor = new SharpSevenZipExtractor("archive.7z"); ``` -------------------------------- ### CreateArchive (Files) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Creates a self-extracting archive from multiple files. ```csharp public void CreateArchive(string[] fileNames, string archiveFileName) ``` ```csharp sfx.CreateArchive( new[] { @"C:\file1.txt", @"C:\file2.doc", @"C:\file3.pdf" }, @"C:\package.exe" ); ``` -------------------------------- ### VolumeFileNames Property Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-extractor.md Gets the list of volume file names for multi-volume archives. ```csharp public ReadOnlyCollection VolumeFileNames { get; } ``` -------------------------------- ### Self-Extracting Archive Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/INDEX.md Quick start pattern for creating a self-extracting archive. ```csharp var sfx = new SharpSevenZipSfx(SfxModule.Installer); sfx.CreateArchive(@"C:\AppFolder", @"C:\Installer.exe"); ``` -------------------------------- ### Compression with Progress Reporting Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-compressor.md Demonstrates how to report compression progress using an event handler. ```csharp var compressor = new SharpSevenZipCompressor(); compressor.Compressing += (s, e) => Console.WriteLine($"Progress: {e.PercentDone}%"); compressor.CompressDirectory(@"C:\Source", @"C:\backup.7z"); ``` -------------------------------- ### Password-Protected Archive Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/INDEX.md Quick start pattern for handling password-protected archives. ```csharp var extractor = new SharpSevenZipExtractor("encrypted.7z", "password"); var files = extractor.ArchiveFileNames; ``` -------------------------------- ### Preserve Directory Structure Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md Demonstrates how to control whether the root directory is included in the archive during compression. ```csharp var compressor = new SharpSevenZipCompressor(); // Include the root folder in the archive compressor.PreserveDirectoryRoot = true; compressor.CompressDirectory(@"C:\MyProject", @"C:\backup.7z"); // Archive contains: MyProject/file.txt, MyProject/subfolder/file2.txt // Or flatten to root compressor.PreserveDirectoryRoot = false; compressor.CompressDirectory(@"C:\MyProject", @"C:\backup.7z"); // Archive contains: file.txt, subfolder/file2.txt ``` -------------------------------- ### CreateArchive (Directory) Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/api-reference/sharp-seven-zip-sfx.md Creates a self-extracting archive from a directory. ```csharp public void CreateArchive(string sourceDirectory, string archiveFileName) ``` ```csharp var sfx = new SharpSevenZipSfx(SfxModule.Default); sfx.CreateArchive(@"C:\SourceDir", @"C:\installer.exe"); ``` -------------------------------- ### Mock Archive For Testing Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/BEST-PRACTICES.md A C# method to create a temporary archive file for testing purposes. ```csharp private string CreateTestArchive() { var tempFile = Path.GetTempFileName() + ".7z"; var testData = Path.Combine(Path.GetTempPath(), "test_data"); try { Directory.CreateDirectory(testData); File.WriteAllText(Path.Combine(testData, "file.txt"), "test content"); var compressor = new SharpSevenZipCompressor(); compressor.CompressDirectory(testData, tempFile); return tempFile; } finally { Directory.Delete(testData, recursive: true); } } ``` -------------------------------- ### ReportErrors Property Source: https://github.com/jeremyansel/sharpsevenzip/blob/main/_autodocs/configuration.md Gets or sets whether to throw exceptions for errors (true) or suppress them (false). ```csharp public bool ReportErrors { get; set; } ```