【发布时间】:2017-06-20 15:55:40
【问题描述】:
我正在尝试将所有文件夹及其内容压缩到一个 zip 文件中。根据我的研究(通过 StackOverflow 和 Microsoft), Directory.CreateDirectory(Path) 应该创建给定的目录。但是,我的 ZipFile 显示为空。
例如,我有一个文件夹 (C:\Users\smelmo\Desktop\test),其中包含子文件夹 (0001, 0002)。 0001 和 0002 内是其他文件。我想将 0001 和 0002 一起压缩到测试文件夹中。这是我目前所拥有的:
// Open the directory of the target folder
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
// Grab each directory within the target folder
foreach (var directoryName in Directory.GetDirectories(strStartPath))
{
// Add each directory to the ZipFile
Directory.CreateDirectory(directoryName);
}
}
这不会产生任何东西。但是,我也有代码可以抓取子文件夹中的所有文件并将它们放在 ZipFile 中。
// Open the directory of the target folder
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
// Grab each directory within the target folder
foreach (var directoryName in Directory.GetDirectories(strStartPath))
{
//Grab all files in each directory
foreach (var filePath in Directory.GetFiles(directoryName))
{
var fileName = Path.GetFileName(@filePath);
// Place each directory and its repsective files in the zip file
var entry = archive.CreateEntryFromFile(filePath, fileName);
}
}
}
但这并没有在其中放置子文件夹 0001 和 0002,只是 0001 和 0002 的内容。我想要 0001 和 0002 以及它们各自的内容。
【问题讨论】:
-
Directory.CreateDirectory仅适用于文件系统,因此您正在重新创建已经存在的目录!见Creating Directories in a ZipArchive