2016-09-27 5 views
3

フォルダ内のすべてのファイルからzipファイルを作成しようとしていますが、関連するスニペットをオンラインで見つけることはできません。私はこのような何かをしようとしています:フォルダ内のすべてのファイルからzipファイルを作成する

DirectoryInfo dir = new DirectoryInfo("somedir path"); 
ZipFile zip = new ZipFile(); 
zip.AddFiles(dir.getfiles()); 
zip.SaveTo("some other path"); 

助けを非常に感謝します。

編集:私はフォルダからファイルを圧縮したいだけで、それはサブフォルダではありません。あなたが持っているかもしれませんが、いくつかのフォルダに

string startPath = @"some path"; 
string zipPath = @"some other path"; 
var files = Directory.GetFiles(startPath); 

using (FileStream zipToOpen = new FileStream(zipPath, FileMode.Open)) 
{ 
    using (ZipArchive archive = new ZipArchive(zipToOpen, ZipArchiveMode.Create)) 
    { 
     foreach (var file in files) 
     { 
      archive.CreateEntryFromFile(file, file); 
     } 
    } 
} 

答えて

8
using System.Compression.IO 

string startPath = @"c:\example\start";//folder to add 
string zipPath = @"c:\example\result.zip";//URL for your ZIP file 
ZipFile.CreateFromDirectory(startPath, zipPath, CompressionLevel.Fastest, true); 
string extractPath = @"c:\example\extract";//path to extract 
ZipFile.ExtractToDirectory(zipPath, extractPath); 

ファイルのみを使用するには、使用:

//Creates a new, blank zip file to work with - the file will be 
//finalized when the using statement completes 
using (ZipArchive newFile = ZipFile.Open(zipName, ZipArchiveMode.Create)) 
{ 
    foreach (string file in Directory.GetFiles(myPath)) 
    { 
     newFile.CreateEntryFromFile(file); 
    }    
} 
+0

ありがとうございます。このサンプルは、フォルダ内のすべてのファイルとフォルダを消去します。私は、フォルダからファイルを圧縮したいだけです。 – SnelleJelle

+0

ええ、確かに - 私がこれに答えたときに私をdownvoteし、OPを指定する前にサブフォルダが含まれないようにしました。 ahem ...これは悪い答えがそれが編集の前に作られたとしたらどうですか? –

+0

私はあなたが私を助けるために時間と労力を費やしたことに非常に感謝しています。サンプルとタイトルの両方は、私がファイルを圧縮したいだけであることを明確に示しました。私はちょうどそれをより明確に述べるべきだと思ったので、編集を追加したのです。 – SnelleJelle

1

プロジェクトでSystem.IO.CompressionSystem.IO.Compression.FileSystemを参照する、あなたのコードは次のようなものになることができます前提の問題

関連する問題