![](/img/trans.png)
[英]System.UnauthorizedAccessException: Access to the path is denied (UWP C#)
[英]UWP System.UnauthorizedAccessException: Access to the path is denied
using(WebClient cln = new WebClient()) {
try {
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("PNG File", new List < string > () {
".png"
});
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
var file = await picker.PickSaveFileAsync();
cln.DownloadFile("https://i.redd.it/o8rz4s0lxp021.png", file.Path);
} catch (Exception e) {
Debug.WriteLine(e);
}
}
當我開始創建這個文件時,它拋出 System.UnauthorizedAccessException 並且文件已損壞。 任何想法有什么問題?
看來你這里有同步問題。 您應該確保在下載內容之前完成FileSavePicker
作業,因為您正在嘗試異步更新文件( await picker.PickSaveFileAsync();
)。 為此,您可以使用FileUpdateStatus
using (WebClient cln = new WebClient())
{
try
{
FileSavePicker picker = new FileSavePicker();
picker.FileTypeChoices.Add("PNG File", new List<string>() { ".png" });
picker.SuggestedStartLocation = PickerLocationId.DocumentsLibrary;
var file = await picker.PickSaveFileAsync();
// Prevent updates to the remote version of the file until we finish making changes and call CompleteUpdatesAsync.
CachedFileManager.DeferUpdates(file);
// write to file
await FileIO.WriteTextAsync(file, file.Name);
// Let Windows know that we're finished changing the file so the other app can update the remote version of the file.
// Completing updates may require Windows to ask for user input.
FileUpdateStatus status = await CachedFileManager.CompleteUpdatesAsync(file);
if (status == FileUpdateStatus.Complete)
{
cln.DownloadFile("https://i.redd.it/o8rz4s0lxp021.png", file.Path);
}
}
catch (Exception e)
{
Debug.WriteLine(e);
}
}
好的,我通過改變這個來修復它:
cln.DownloadFile("https://i.redd.it/o8rz4s0lxp021.png", file.Path);
到背景下載器:
BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(new Uri("https://i.redd.it/o8rz4s0lxp021.png"), file);
await download.StartAsync();
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.