I am trying create zip in UWP app. I need create zip in custom location, so I am using folder picker. But if I select folder to save zip, the access to this patch is denied if I am creating zip to this patch.
Here is my code:
public async Task CreateZipFile2()
{
Windows.Storage.StorageFolder storageFolder = Windows.Storage.ApplicationData.Current.LocalFolder;
var folderPicker = new Windows.Storage.Pickers.FolderPicker();
folderPicker.SuggestedStartLocation = Windows.Storage.Pickers.PickerLocationId.Desktop;
folderPicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFolder folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
Windows.Storage.AccessCache.StorageApplicationPermissions.FutureAccessList.AddOrReplace("PickedFolderToken", folder);
await Task.Run(() =>
{
ZipFile.CreateFromDirectory($"{storageFolder.Path}\\source", $"{folder.Path}\\e.zip", CompressionLevel.NoCompression, false);
});
}
}
Thanks for helps.
CodePudding user response:
This is expected behavior. The destination file is not accessible in such a scenario when using the ZipFile.CreateFromDirectory Method because it's a desktop API. It works differently from the UWP native Storage API.
When you use the folder picker to pick the target folder, your app will gain permission to access the target folder, but this works for the Storage API. ZipFile API tries to open the path directly using System.IO instead of Windows.Storage API and it failed.
For locations like the local folder, which the UWP app has all the permission for, the ZipFile API will work. For example, you could change the destination folder into local folder and it will work. Like this:
ZipFile.CreateFromDirectory($"{storageFolder.Path}\\source", $"{storageFolder.Path}\\e.zip", CompressionLevel.NoCompression, false);
My suggestion is that you could create the zip file in the local folder, and then use the StorageFile.CopyAsync Method to copy the file to the destination folder which the user chooses.
Like this:
StorageFile file = await storageFolder.GetFileAsync("e.zip");
await file.CopyAsync(folder);
Then you just need to delete the old file in the local folder.