2016-04-01 12 views
2

を維持し、ZIPから特定のディレクトリを抽出しますディスクが、そうやっている間、私は、フォルダ構造をperserveすることができないんだ、と代わりにC#が、私はzipアーカイブとアーカイブの内部のフォルダ構造を持ってこのようになりますフォルダ構造

- fileA.txt 
    + dirB 
    - fileB.txt 

の私は

- fileA.txt 
    - fileB.txt 
を取得します私は Path.Combine()に代わり entry.FullNameentry.Nameを使用しているため、それはだかなり肯定的だが、私は FullNameを使用した場合、私はルートディレクトリ dirA私はパスでなければなりません

using (ZipArchive archive = ZipFile.OpenRead(archivePath)) // archivePath is path to the zip archive 
{ 
    // get the root directory 
    var root = archive.Entries[0]?.FullName; 
    if (root == null) { 
     // quit in a nice way 
    } 
    var result = from curr in archive.Entries 
       where Path.GetDirectoryName(curr.FullName) != root 
       where !string.IsNullOrEmpty(curr.Name) 
       select curr; 

    foreach (ZipArchiveEntry entry in result) 
    { 
     string path = Path.Combine(extractPath, entry.Name); // extractPath is somwhere on the disk 
     entry.ExtractToFile(path); 
    } 
} 

は、ここに私のコードです抽出しないことを試みる。 だから私はここで壁にヒットしました、と私は考えることができる唯一の解決策は、と全体のzipファイルを解凍します

ZipFile.ExtractToDirectory(archivePath, extractPath); 

...そして別の場所にdirAからサブフォルダを移動するとdirAを削除します。幸運な考えのようには見えない。

ご迷惑をおかけして申し訳ありません。

答えて

3

あなたはちょうどあなたがいけないパスの一部でフルネームを短縮することができます:

foreach (ZipArchiveEntry entry in result) 
{ 
    var newName = entry.FullName.Substring(root.Length); 
    string path = Path.Combine(extractPath, newName); 

    if (!Directory.Exists(path)) 
     Directory.CreateDirectory(Path.GetDirectoryName(path)); 

    entry.ExtractToFile(path); 
} 
+0

はなぜ、それは偉大な回避策だとそれが今ではあたりまえのようです!ありがとう。 – nn2202

関連する問題