2014-06-14 135 views
0

我正在處理解壓縮zip文件,其中一些文件層次結構爲本地文件夾。我嘗試了ZipArchive,但擴展方法winct不支持ExtractToDirectory。一些其他的可能性是DotNetZip和SharpZipLib,但這些庫在winrt上也不支持。Winrt - 解壓縮文件層次結構

郵編層次文件可以是這樣的(我假設層次最高2的深度):
文件夾1/picture1.jpg
文件夾1/picture2.jpg
文件夾2/picture1.jpg
文件夾2/picture2.jpg

一些簡單的代碼示例:

var data = await client.GetByteArrayAsync("..../file.zip"); 

var folder = Windows.Storage.ApplicationData.Current.LocalFolder; 
var option = Windows.Storage.CreationCollisionOption.ReplaceExisting; 

var file = await folder.CreateFileAsync("file.zip", option); 
Windows.Storage.FileIO.WriteBytesAsync(file, data); 

// zip is saved to Local folder and now I need extract files hierarchy from this zip 

你有這個問題,一些聰明的和簡單的解決方案?你知道一些有用的圖書館,用於winrt或便攜式類庫的nuget包嗎?

回答

2

一些擴展方法,我必須使用ZipArchive處理這些東西。

public static async Task<IStorageItem> CreatePath(this StorageFolder folder, string fileLocation, CreationCollisionOption fileCollisionOption, CreationCollisionOption folderCollisionOption) 
{ 
    var localFilePath = PathHelper.ToLocalPath(fileLocation).Replace(PathHelper.ToLocalPath(folder.Path), ""); 
    if (localFilePath.Length > 0 && (localFilePath[0] == '/' || localFilePath[0] == '\\')) 
    { 
     localFilePath = localFilePath.Remove(0, 1); 
    } 

    if (localFilePath.Length == 0) 
    { 
     return folder; 
    } 

    var separatorIndex = localFilePath.IndexOfAny(new char[] { '/', '\\' }); 
    if (separatorIndex == -1) 
    { 
     return await folder.CreateFileAsync(localFilePath, fileCollisionOption); 
    } 
    else 
    { 
     var folderName = localFilePath.Substring(0, separatorIndex); 
     var subFolder = await folder.CreateFolderAsync(folderName, folderCollisionOption); 
     return await subFolder.CreatePath(fileLocation.Substring(separatorIndex + 1), fileCollisionOption, folderCollisionOption); 
    } 
} 

public static async Task ExtractToFolderAsync(this ZipArchive archive, StorageFolder folder) 
{ 
    foreach (var entry in archive.Entries) 
    { 
     var storageItem = await folder.CreatePathAsync(entry.FullName, CreationCollisionOption.OpenIfExists, CreationCollisionOption.OpenIfExists); 
     StorageFile file; 
     if ((file = storageItem as StorageFile) != null) 
     { 
      using (var fileStream = await file.OpenStreamForWriteAsync()) 
      { 
       using (var entryStream = entry.Open()) 
       { 
        await entryStream.CopyToAsync(fileStream); 
       } 
      } 
     } 
    } 
} 
+0

我也想過這樣的解決方案。但是,感謝你的代碼。 –

+0

@Jon R你能描述一下PathHelper類嗎? –

+0

你從哪裏得到PathHelper?任何鏈接? –