例如,如果我有一個名爲2016的文件夾,並且該文件夾內有文件夾Jan-Dec和其他文件,是否可以將這些文件夾一起壓縮到2016.zip中?我試過的任何東西都將文件夾中的所有文件壓縮在一起,但我想壓縮在一起只是文件夾中的文件夾和其他文件。是否可以在c#中將文件夾壓縮在一起?
基本上,它將是2016.zip與2016.zip中的每月文件夾中的每個文件夾中的每個文件夾中的Jan-Dec文件夾,而不是zip中的空文件夾。
下面的代碼抓取從00開始但不是文件夾的文件。
// Where the files are located
string strStartPath = txtTargetFolder.Text;
// Where the zip file will be placed
string strZipPath = @"C:\Users\smelmo\Desktop\testFinish\" + strFileNameRoot + "_" + txtDateRange1.Text.Replace(@"/", "_") + "_" + txtDateRange2.Text.Replace(@"/", "_") + ".zip";
if(File.Exists(strZipPath))
{
File.Delete(strZipPath);
}
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
{
if (file.Name.StartsWith("00"))
{
var entry = archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
}
}
}
我也使用typeof()
嘗試,但它不搶的文件夾,或任何東西。
using (ZipArchive archive = ZipFile.Open(strZipPath, ZipArchiveMode.Create))
{
foreach (FileInfo file in new DirectoryInfo(strStartPath).GetFiles())
{
Type t = file.GetType();
if (t.Equals(typeof(Directory)))
{
var entry = archive.CreateEntryFromFile(Path.Combine(file.Directory.ToString(), file.Name), file.Name);
}
}
編輯:添加細節爲了清楚
只是爲了澄清,你要空文件夾的壓縮,對不對? –
@ CodyG.No,Jan-Dec文件夾中會包含文件。我想將Jan-Dec文件夾壓縮在一起。因此,打開2016.zip將有1月至12月文件夾,然後這些文件夾有其各自的文件。 – smelmo
你爲什麼不試試'DirectoryInfo(strStartPath).GetDirectories'? '.GetFiles()'不會返回目錄... –