我正在尝试使用PickMultipleFilesAsync()将多个文件添加到已创建的ZIP文件中。我以前使用FilesavePicker.PickSaveFileAsync()
方法以相同的代码创建了要访问的ZIP文件。该应用程序在笔记本电脑的Windows 10 Pro 1803版上运行,我使用Visual Studio Community 2017进行创建。
我得到的问题是,按照FileOpenPicker MSDN页面中所述的步骤进行操作之后,我得到了 System.UnauthorizedAccessException:'对路径'C:\ Users \'User'\ Downloads的访问{ZIP文件}'被拒绝。'
我创建了ZIP文件,并尝试使用以下代码添加新文件:
StorageFile file = await savePicker.PickSaveFileAsync();
if (file != null)
{
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
try
{
Stream stream = await file.OpenStreamForWriteAsync();
using (ZipArchive archive = new ZipArchive(stream, ZipArchiveMode.Update))
{
// This line works fine, file is added
archive.CreateEntryFromFile(path_to_another_file, file_name_in_ZIP);
//....
var dialog = new MessageDialog("Do you want to add more files to ZIP?");
//... (dialog configuration for Yes/No options)
var result = await dialog.ShowAsync();
if(result.Label == "Yes")
{
Debug.WriteLine("Yes option was selected!");
// Include additional files
var openPicker = new FileOpenPicker();
openPicker.FileTypeFilter.Add("*");
openPicker.SuggestedStartLocation = PickerLocationId.Downloads;
IReadOnlyList<StorageFile> addedFiles = await openPicker.PickMultipleFilesAsync();
if (addedFiles.Count > 0)
{
// Application now has read/write access to the picked file(s)
foreach (StorageFile addedFile in addedFiles)
{
Debug.WriteLine(addedFile.Path); // No problem here
// I get the UnauthorizedAccessException here:
archive.CreateEntryFromFile(addedFile.Path, @"additional files/" + addedFile.Name);
}
}
else
{
// Update log file
globalLog += GetTime() + "No additional files";
}
}
}
}
}
我已经在appxmanifest中添加了<rescap:Capability Name="broadFileSystemAccess"/>
,以防万一,但是由于我可以使用FileOpenPicker访问选定的文件,所以我认为这不是问题。
在此代码中创建ZIP文件时,我仍然应该可以访问它,对吗?我怀疑FileOpenPicker会以某种方式“关闭”对ZIP文件的访问以便授予对要添加的文件的访问,或者MessageDialog阻止访问我在调用showAsync()之后创建的ZIP文件。
还有其他方法可以实现我正在尝试的功能吗?
编辑:尽管我可以在调试控制台中显示文件名,但是我无法访问使用FileOpenPicker选择的文件。 ZIP文件访问正常。
答案 0 :(得分:2)
我刚刚找到了解决方案。如here所述,您可以使用缓冲区将文件内容流式传输到ZIP文件,只需替换:
RewriteEngine On
# ensure www.
RewriteCond %{HTTP_HOST} !^www\. [NC]
RewriteRule ^ https://www.%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
# ensure https
RewriteCond %{HTTP:X-Forwarded-Proto} !https
RewriteCond %{HTTPS} off
RewriteRule ^ https://%{HTTP_HOST}%{REQUEST_URI} [L,R=301]
使用:
// I get the UnauthorizedAccessException here:
archive.CreateEntryFromFile(addedFile.Path, @"additional files/" + addedFile.Name);
这样,就添加了文件,并且没有发生ZipArchiveEntry readmeEntry = archive.CreateEntry(@"additional files/" + addedFile.Name);
byte[] buffer = WindowsRuntimeBufferExtensions.ToArray(await FileIO.ReadBufferAsync(addedFile));
using (Stream entryStream = readmeEntry.Open())
{
await entryStream.WriteAsync(buffer, 0, buffer.Length);
}
。希望这对遇到同样问题的人有所帮助!