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

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

问题描述

 私有的

我在Windows 8 C#应用程序中有如下代码:异步任务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());
等待writer.StoreAsync();
writer.DetachStream();
等待fs.FlushAsync();
writer.Dispose();

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

}
catch(异常e)
{
return;
}

image1.Source = image;
}

看来我在这个特定的行上随机获取错误:

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

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


UnauthorizedAccessException被捕获



访问被拒绝。 (从HRESULT的异常:0x80070005
(E_ACCESSDENIED))
System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(任务
任务)在
System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification (Task
任务)在System.Runtime.CompilerServices.TaskAwaiter`1.GetResult()
在TestApp.MainPage.d__4.MoveNext()在
d:\TestApp\TestApp\ MainPage.xaml.cs:line 86



解决方案

更新 - 拒绝访问错误是是由多件事引起的。



第一个原因与图像的下载有关。看来下载代码正在拿着打开文件。我已经简化了以下下载代码。



第二个原因与 BitmapImage 对象持有打开文件。看到这篇文章了解更多信息:访问在删除WinRT中以前在DataTemplate中使用的图像文件时被拒绝



第二个问题的一个方法是使用 / code>而不是 Uri 来初始化 BitmapImage



这是一个适用于我的版本(您的原始代码也在这里,但已注释掉):

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

if(Uri.TryCreate(imageFile.Path,UriKind.RelativeOrAbsolute,out imageUri))
{
image = new BitmapImage(imageUri);
}
* /
var fs = await imageFile.OpenStreamForWriteAsync();
等待response.Content.CopyToAsync(fs);
等待fs.FlushAsync();
//您可能希望将此Dispose作为
// finally块的一部分(try / catch / finally)
fs.Dispose();

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


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天全站免登陆