UnauthorizedAccessException同时保存文件 [英] UnauthorizedAccessException while saving a file

查看:251
本文介绍了UnauthorizedAccessException同时保存文件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下的code,其中从一台服务器和存储获取图像的Windows 8的C#应用​​程序是:

 专用异步任务httpFetcher()
    {
        HttpClient的HttpClient的=新的HttpClient();
        HTT prequestMessage要求=新HTT prequestMessage(
HttpMethod.Gethttp://www.example.com/fakeImageRotator.php); // 例如
        HTT presponseMessage响应=等待httpClient.SendAsync(的要求,
            HttpCompletionOption.ResponseHeadersRead);        乌里imageUri;
        BitmapImage的图像= NULL;        尝试
        {
            VAR镜像文件=等待ApplicationData.Current.LocalFolder.CreateFileAsync(
         test.png,CreationCollisionOption.ReplaceExisting);
            变种FS =等待imageFile.OpenAsync(FileAccessMode.ReadWrite);
            DataWriter作家=新DataWriter(fs.GetOutputStreamAt(0));
            writer.WriteBytes(等待response.Content.ReadAsByteArrayAsync());
            等待writer.StoreAsync();
            writer.DetachStream();
            等待fs.FlushAsync();
            writer.Dispose();            如果(Uri.TryCreate(imageFile.Path,UriKind.RelativeOrAbsolute,出imageUri))
            {
                图像=新的BitmapImage(imageUri);
            }        }
        赶上(例外五)
        {
            返回;
        }        image1.Source =图像;
    }

看来,笔者随机得到这一行错误:

  VAR镜像文件=等待ApplicationData.Current.LocalFolder.CreateFileAsync(
         test.png,CreationCollisionOption.ReplaceExisting);

这并不总是发生,所以我不知道如何确定问题。所有错误的详细信息在这里:


  

UnauthorizedAccessException被抓获


  
  

访问被拒绝。 (异常来自HRESULT:0X80070005
  (E_ACCESSDENIED))在
  System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务
  任务)在
  System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(任务
  任务)在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
  在TestApp.MainPage.d__4.MoveNext()的
  D:\\ TestApp \\ TestApp \\ MainPage.xaml.cs中:第86行



解决方案

更​​新 - 拒绝访问错误是由多个因素引起。

第一个原因具有与图像的下载做。看来东西在下载code持有打开该文件。我已经简化下面的下载code。

第二个原因先后与的BitmapImage 对象举行公开文件做。看到这个帖子的详细信息:<一href=\"http://social.msdn.microsoft.com/Forums/en-US/winappswithcsharp/thread/ece23cfd-996d-41c5-8add-188db000c2d0/\">Access删除图像文件$ P $中的DataTemplate pviously使用WinRT中

当被拒绝

周围的第二个问题的方法之一是使用,而不是乌里来初始化<$ C一流$ C>的BitmapImage

下面是我(原为code也是在这里,但注释掉)使用的版本:

  VAR镜像文件=等待ApplicationData.Current.LocalFolder.CreateFileAsync(
  test.png,CreationCollisionOption.ReplaceExisting);
/ *
变种FS =等待imageFile.OpenAsync(FileAccessMode.ReadWrite);
DataWriter作家=新DataWriter(fs.GetOutputStreamAt(0));
writer.WriteBytes(等待response.Content.ReadAsByteArrayAsync());
等待writer.StoreAsync();
writer.DetachStream();
等待fs.FlushAsync();
writer.Dispose();如果(Uri.TryCreate(imageFile.Path,UriKind.RelativeOrAbsolute,出imageUri))
{
    图像=新的BitmapImage(imageUri);
}
* /
变种FS =等待imageFile.OpenStreamForWriteAsync();
等待response.Content.CopyToAsync(FS);
等待fs.FlushAsync();
//你可能需要有这种电池作为一部分
// finally块(的try / catch /最后)
fs.Dispose();变种BS =等待imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read);
图像=新的BitmapImage();
image.SetSource(BS);
...
image1.Source =图像;

I have the following code in a Windows 8 C# app which fetches an image from a server and stores it:

        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;
    }

It appears that I randomly get errors on this particular line:

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

It doesn't always happen, so I'm not sure how to pinpoint the issue. All the error details are here:

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

解决方案

Update - The "Access Denied" errors are being caused by multiple things.

The first cause has to do with the downloading of the image. It appears something in download code is holding open the file. I have simplified the download code below.

The second cause has to do with the BitmapImage object holding open the file. See this post for more info: Access Denied when deleting image file previously used in DataTemplate in WinRT

One way around the second issue is to use a stream instead of a Uri to initialize the BitmapImage.

Here is a version that works for me (your original code is also here, but commented out):

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;

这篇关于UnauthorizedAccessException同时保存文件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆