UWP System.UnauthorizedAccessException:拒绝访问路径

时间:2020-01-22 11:13:19

标签: c# uwp

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且文件已损坏。有什么想法吗?

2 个答案:

答案 0 :(得分:0)

似乎您在这里有同步问题。由于要尝试异步更新文件(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);
    }
}

答案 1 :(得分:0)

好,我通过更改此方法来解决它:

cln.DownloadFile("https://i.redd.it/o8rz4s0lxp021.png", file.Path); 到BackgroundDownloarder:

BackgroundDownloader downloader = new BackgroundDownloader();
DownloadOperation download = downloader.CreateDownload(new Uri("https://i.redd.it/o8rz4s0lxp021.png"), file);
await download.StartAsync();