解压缩文件层次结构
本文关键字:层次结构 文件 解压缩 | 更新日期: 2023-09-27 18:08:47
我正在处理解压缩压缩文件与一些层次结构的文件到本地文件夹。我尝试了ZipArchive,但扩展方法ExtractToDirectory在winrt上不受支持。其他一些可能是DotNetZip和SharpZipLib,但这些库在winrt上也不支持。
Zip层次结构文件看起来像这样(我假设层次结构的深度为最大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包或者可移植类库?
一些扩展方法我必须使用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);
}
}
}
}
}