我在 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 被捕获
访问被拒绝。(来自 HRESULT 的异常:0x80070005 (E_ACCESSDENIED))在 System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerNotification(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess(Task task) 在 System.Runtime.CompilerServices.TaskAwaiter`1.GetResult () 在 TestApp.MainPage.d__4.MoveNext() 在 d:\TestApp\TestApp\MainPage.xaml.cs:line 86