本文介绍了StorageFile.OpenAsync中的UnauthorizedAccessException的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我使用下面的代码来下载/保存图像并稍后打开它,但是在以后的OpenAsync中,它会抛出UnauthorizedAccessException,似乎文件没有关闭,但实际上IRandomAccessStream / DataWriter已被处理掉了。
I used the following code to download/save an image and open it later, but in later OpenAsync, it throws the UnauthorizedAccessException, it seems that the file is not close, but actually the IRandomAccessStream/DataWriter has been disposed.
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(HttpMethod.Get, "http://www.silverlightshow.net/Storage/Users/nikolayraychev/Perspective_Transforms_4.gif");
HttpResponseMessage response = await httpClient.SendAsync(request, HttpCompletionOption.ResponseHeadersRead);
//Write Image File
StorageFile imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync("test.gif", CreationCollisionOption.ReplaceExisting);
using (IRandomAccessStream fs = await imageFile.OpenAsync(FileAccessMode.ReadWrite))
{
using (DataWriter writer = new DataWriter(fs.GetOutputStreamAt(0)))
{
writer.WriteBytes(await response.Content.ReadAsByteArrayAsync());
await writer.StoreAsync();
writer.DetachStream();
await fs.FlushAsync();
}
}
StorageFile imageFile1 = await ApplicationData.Current.LocalFolder.GetFileAsync("test.gif");
//Exception is throwed here
using (IRandomAccessStream stream = await imageFile1.OpenAsync(FileAccessMode.Read))
{
BitmapImage img = new BitmapImage();
img.SetSource(stream);
}
推荐答案
我遇到了同样的问题,必须在流完成之前明确地处理流和文件对象。
I had the same issue and had to explicitly dispose the stream and file objects before it would complete.
var file = await ApplicationData.Current.LocalFolder.CreateFileAsync(filename, Windows.Storage.CreationCollisionOption.ReplaceExisting);
using (var fs = await file.OpenAsync(Windows.Storage.FileAccessMode.ReadWrite))
{
var outStream = fs.GetOutputStreamAt(0);
var dataWriter = new Windows.Storage.Streams.DataWriter(outStream);
dataWriter.WriteString("Hello from Test!");
await dataWriter.StoreAsync();
dataWriter.DetachStream();
await outStream.FlushAsync();
outStream.Dispose(); //
fs.Dispose();
}
这篇关于StorageFile.OpenAsync中的UnauthorizedAccessException的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!