c# - 保存文件时出现 UnauthorizedAccessException

标签 c# asynchronous windows-8 error-handling unauthorizedaccessexcepti

我在 Windows 8 C# 应用程序中有以下代码,它从服务器获取图像并将其存储:

        private async Task httpFetcher()
    {
        HttpClient httpClient = new HttpClient();
        HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, "http://www.example.com/fakeImageRotator.php"); // FOR EXAMPLE
        HttpResponseMessage response = await httpClient.SendAsync(request,
            HttpCompletionOption.ResponseHeadersRead);

        Uri imageUri;
        BitmapImage image = null;

        try
        {
            var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
         "test.png", CreationCollisionOption.ReplaceExisting);
            var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
            DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
            writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
            await writer.StoreAsync();
            writer.DetachStream();
            await fs.FlushAsync();
            writer.Dispose();

            if (Uri.TryCreate(imageFile.Path, UriKind.RelativeOrAbsolute, out imageUri))
            {
                image = new BitmapImage(imageUri);
            }

        }
        catch (Exception e)
        {
            return;
        }

        image1.Source = image;
    }

似乎我在这一行随机出现错误:

                var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
         "test.png", CreationCollisionOption.ReplaceExisting);

它并不总是发生,所以我不确定如何查明问题。所有错误详情都在这里:

UnauthorizedAccessException was caught

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) at System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) at System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) at System.Runtime.CompilerServices.TaskAwaiter`1.GetResult() at TestApp.MainPage.d__4.MoveNext() in d:\TestApp\TestApp\MainPage.xaml.cs:line 86

最佳答案

更新 - “拒绝访问”错误是由多种原因引起的。

第一个原因与图像的下载有关。似乎下载代码中的某些内容正在打开文件。我简化了下面的下载代码。

第二个原因与打开文件的 BitmapImage 对象有关。有关详细信息,请参阅此帖子:Access Denied when deleting image file previously used in DataTemplate in WinRT

解决第二个问题的一种方法是使用 stream 而不是 Uri 来初始化 BitmapImage

这是一个适合我的版本(你的原始代码也在这里,但被注释掉了):

var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
  "test.png", CreationCollisionOption.ReplaceExisting);
/*
var fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
writer.Dispose();

if (Uri.TryCreate(imageFile.Path, UriKind.RelativeOrAbsolute, out imageUri))
{
    image = new BitmapImage(imageUri);
}
*/
var fs = await imageFile.OpenStreamForWriteAsync();
await response.Content.CopyToAsync(fs);
await fs.FlushAsync();
// you may want to have this Dispose as part of a 
// finally block (try/ catch/ finally)
fs.Dispose();

var bs = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
image = new BitmapImage();
image.SetSource(bs);
...
image1.Source = image;

关于c# - 保存文件时出现 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17000137/

相关文章:

c# - 在 C# 中更新公共(public) "Constants"的正式正确方法

windows - easy_install.exe 权限在 Windows 8 上被拒绝

css - 在 Windows 8 上删除 IE1 1's "clear field"X button

c# - 控件和线程

c# - visual studio 2017 发布 asp.net core

c# - 以文化不敏感的方式序列化/反序列化数据的正确方法是什么?

c# - Entity Framework 核心 + SQlite。异步请求实际上是同步的

kotlin - 为什么我不能使用try/catch来捕获Kotlin协程中的异常?

javascript - 异步调用解决方法

javascript - 如何在 Windows 8 中进行 JSON 解析