gpt4 book ai didi

c# - StorageFile.OpenAsync 中的 UnauthorizedAccessException

转载 作者:太空狗 更新时间:2023-10-30 00:54:55 25 4
gpt4 key购买 nike

我用下面的代码下载/保存了一张图片,稍后打开,但是在后面的OpenAsync中,抛出了UnauthorizedAccessException,看起来是文件没有关闭,实际上IRandomAccessStream/DataWriter已经被处理掉了。

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

最佳答案

我有同样的问题,必须在完成之前显式处理流和文件对象。

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

关于c# - StorageFile.OpenAsync 中的 UnauthorizedAccessException,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/11168143/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com