我想使用 SevenZipCompressor 将 3 个文件夹压缩成一个文件。我知道如何压缩单个文件夹。这样的事情可能吗??
谢谢 !
我想使用 SevenZipCompressor 将 3 个文件夹压缩成一个文件。我知道如何压缩单个文件夹。这样的事情可能吗??
谢谢 !
该类SevenZipCompressor
提供了一个名为CompressFileDictionary()
. 方法重载之一需要文件字典和文件流。文件字典是一个普通的 .Net Dictionary<string,string>
。字典的键是档案中文件的名称(或相对路径),字典的值是文件系统中文件的路径。
字典的键允许您控制 7z 存档中的结构。例如如果你想压缩这三个文件夹
c:\temp\testdir1
|- file1.txt
|- file2.txt
c:\temp\testdir2
|- file1.txt
c:\temp2\test
|- file3.txt
并且存档中的结果结构应该是
testdir1
|- file1.txt
|- file2.txt
testdir2
|- file1.txt
test
|-file3.txt
然后只需按以下方式将文件添加到字典中:
Dictionary<string, string> filesDic = new Dictionary<string, string>();
filesDic.Add(@"testdir1\file1.txt", @"c:\temp\testdir1\files1.txt");
filesDic.Add(@"testdir1\file2.txt", @"c:\temp\testdir1\files2.txt");
filesDic.Add(@"testdir2\file1.txt", @"c:\temp\testdir2\files1.txt");
filesDic.Add(@"test\file3.txt", @"c:\temp2\test\files3.txt");
下面的示例仅显示了如何自动为文件夹创建此类字典并将其压缩为单个 7z 存档文件的过程。
private static void AddFilesFromDirectoryToDictionary(Dictionary<string, string> filesDictionary,
string pathToDirectory)
{
DirectoryInfo dirInfo = new DirectoryInfo(pathToDirectory);
FileInfo[] fileInfos = dirInfo.GetFiles("*.*", SearchOption.AllDirectories);
foreach (FileInfo fi in fileInfos)
{
filesDictionary.Add(fi.FullName.Replace(dirInfo.Parent.FullName + "\\", "").ToLower(),
fi.FullName);
}
}
static void Main(string[] args)
{
// Set path to 7z library.
SevenZipCompressor.SetLibraryPath("7z.dll");
using (FileStream fs = new FileStream("c:\\temp\\test.7z", FileMode.Create))
{
SevenZipCompressor szc = new SevenZipCompressor
{
CompressionMethod = CompressionMethod.Lzma,
CompressionLevel = CompressionLevel.Normal,
CompressionMode = CompressionMode.Create,
DirectoryStructure = true,
PreserveDirectoryRoot = false,
ArchiveFormat = OutArchiveFormat.SevenZip
};
Dictionary<string, string> filesDictionary = new Dictionary<string, string>();
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp\testdir1");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp\testdir2");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp2\test");
szc.CompressFileDictionary(filesDictionary, fs);
}
}
您还可以使用以下代码更改创建ZIP 存档:
using (FileStream fs = new FileStream("c:\\temp\\test.zip", FileMode.Create))
{
SevenZipCompressor szc = new SevenZipCompressor
{
CompressionMethod = CompressionMethod.Deflate,
CompressionLevel = CompressionLevel.Normal,
CompressionMode = CompressionMode.Create,
DirectoryStructure = true,
PreserveDirectoryRoot = false,
ArchiveFormat = OutArchiveFormat.Zip
};
Dictionary<string, string> filesDictionary = new Dictionary<string, string>();
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp\testdir1");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp\testdir2");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:\temp2\test");
szc.CompressFileDictionary(filesDictionary, fs);
}