2017-06-12 11 views
0

たとえば、2016という名前のフォルダがあり、そのフォルダ内にフォルダJan-Decと他のファイルがある場合、それらのフォルダを一緒に2016.zipに圧縮する方法はありますか?私が試みたものは、フォルダ内のすべてのファイルを一緒に圧縮しますが、一緒にジッパーしたいだけです。フォルダ内に他のファイルはありません。C#でフォルダをまとめて圧縮することはできますか?

基本的には、それはそれで、それぞれのファイルを持つフォルダのそれぞれと2016.zip 1月 - 12月のフォルダではなく、ジップで空のフォルダを2016.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); 
       }    
    } 

EDIT:は、次のフォルダ構造を明瞭

+0

空のフォルダのジップが必要ですか? –

+0

@ CodyG.Noの場合、Jan-Decフォルダにはファイルがあります。私はJan-Decフォルダを一緒に圧縮したいと思うでしょう。したがって、2016.zipを開くとJan-Decフォルダが作成され、それぞれのファイルがあるフォルダが作成されます。 – smelmo

+1

'DirectoryInfo(strStartPath).GetDirectories'を試してみませんか? '.GetFiles()'はディレクトリを返さないでしょう... –

答えて

2

の詳細を追加しました:

enter image description here

このコード(更新):

using System.IO; 
using System.IO.Compression; 

class Program 
{ 
    static void Main(string[] args) 
    { 
     string sourceFolder = @"c:\temp"; 
     string zipFilePath = Path.Combine(sourceFolder, "test.zip"); 

     // TODO: Check if the archive exists maybe? 

     using (ZipArchive archive = ZipFile.Open(zipFilePath, ZipArchiveMode.Create)) 
     { 
      foreach (var directoryName in Directory.GetDirectories(sourceFolder)) 
      { 
       foreach (var filePath in Directory.GetFiles(directoryName)) 
       { 
        var dirInfo = new DirectoryInfo(directoryName); 
        var fileName = Path.GetFileName(filePath); 

        var entry = archive.CreateEntry($"{dirInfo.Name}\\{fileName}"); 
       } 
      } 
     } 
    } 
} 

このジッパーを生成:

enter image description here

+0

しかし、.txtファイルの代わりにzipをフォルダにしたいのであれば、最後の 'foreach'を取り出して各directoryNameのエントリを作成すればいいですか? – smelmo

+0

あなたは何を意味するのか正確には分かりません。 Jan-Decという空のフォルダがあるジップだけが必要ですか? –

+0

私はまた、正確なコード(sourceFolderを変更する)を使用しようとしましたが、zipは空です。 – smelmo

関連する問題