如何使用SevenZipSharp向7-zip归档指定路径添加文件?
Got it, I've run into this exact issue before with SevenZipSharp—you're right that the CompressFiles method doesn't expose an overload to set internal archive paths directly. But don't worry, there's a perfect workaround using the CompressFilesDictionary method, which lets you map each source file to its desired path inside the archive.
Step-by-Step Solution
Here's how to implement this:
Initialize the SevenZipCompressor
First, make sure you've set the path to your7z.dll(critical for SevenZipSharp to function) and configured the compressor with your preferred settings.Create a Dictionary to Map Source Files to Internal Paths
Use aDictionary<string, string>where:- The key is the full path to your local file (e.g.,
C:\MyFiles\report.pdf) - The value is the exact path you want the file to have inside the archive (e.g.,
a/b/c/report.pdfor@"a\b\c\report.pdf"—both separators work, but escaped backslashes or forward slashes are safest)
- The key is the full path to your local file (e.g.,
Call
CompressFilesDictionary
This method takes the output archive path and your mapping dictionary, handling the rest automatically.
Full Code Example
using SevenZip; using System.Collections.Generic; // Set the path to your 7z.dll (match 32/64-bit architecture to your app) SevenZipBase.SetLibraryPath(@"C:\Your\Path\To\7z.dll"); // Initialize the compressor with your desired settings var compressor = new SevenZipCompressor { ArchiveFormat = OutArchiveFormat.SevenZip, CompressionMode = CompressionMode.Create, // Use CompressionMode.Append to add to an existing archive CompressionLevel = CompressionLevel.Normal }; // Create your source-to-internal-path mapping var fileMappings = new Dictionary<string, string> { // Local file path -> Internal archive path { @"C:\LocalFiles\notes.txt", @"a\b\c\notes.txt" }, { @"C:\LocalFiles\logo.png", @"a\b\c\assets\brand-logo.png" } // You can rename files in the archive too }; // Execute the compression try { compressor.CompressFilesDictionary(@"C:\Output\myArchive.7z", fileMappings); Console.WriteLine("Files added successfully to the specified archive paths!"); } catch (SevenZipException ex) { Console.WriteLine($"Error during compression: {ex.Message}"); }
Key Notes
- Archive Path Separators: Both forward slashes (
/) and escaped backslashes (\\) work for internal paths. Using verbatim strings (@"...") avoids having to escape backslashes repeatedly. - Existing Archives: If you want to add files to an already existing archive, set
CompressionMode = CompressionMode.Appendinstead ofCreate. - DLL Compatibility: Ensure your
7z.dllmatches your application's architecture (32-bit vs 64-bit) and is compatible with your version of SevenZipSharp. Mismatches will cause runtime errors. - Renaming Files: The dictionary lets you rename files as you add them—just set the value to the desired filename in the internal path (like the
logo.png→brand-logo.pngexample above).
内容的提问来源于stack exchange,提问作者HerpDerpington

