我想使用SevenZipCompressor将3个文件夹压缩到一个文件中。我知道如何压缩一个文件夹。这样的事情可能吗??
谢谢!
SevenZipCompressor
类提供了一个名为CompressFileDictionary()
的方法。其中一个方法重载需要一个文件字典和一个文件流。文件字典是一个普通的.Net Dictionary<string,string>
。字典的关键字是中文件的名称(或相对路径)档案,字典的值是文件系统中文件的路径。
字典的键允许您控制7z档案中的结构。例如,如果你想压缩三个文件夹
c:temptestdir1
|- file1.txt
|- file2.txt
c:temptestdir2
|- file1.txt
c:temp2test
|- file3.txt
档案中的结果结构应该是
testdir1
|- file1.txt
|- file2.txt
testdir2
|- file1.txt
test
|-file3.txt
然后按照以下方式将文件添加到dictionary中:
Dictionary<string, string> filesDic = new Dictionary<string, string>();
filesDic.Add(@"testdir1file1.txt", @"c:temptestdir1files1.txt");
filesDic.Add(@"testdir1file2.txt", @"c:temptestdir1files2.txt");
filesDic.Add(@"testdir2file1.txt", @"c:temptestdir2files1.txt");
filesDic.Add(@"testfile3.txt", @"c:temp2testfiles3.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:temptestdir1");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:temptestdir2");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:temp2test");
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:temptestdir1");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:temptestdir2");
AddFilesFromDirectoryToDictionary(filesDictionary, @"c:temp2test");
szc.CompressFileDictionary(filesDictionary, fs);
}