我有以下代码从Windows 8应用程序中的Web服务器获取动态图像。
private async Task httpFetcher()
{
HttpClient httpClient = new HttpClient();
HttpRequestMessage request = new HttpRequestMessage(
HttpMethod.Get, "http://www.reignofcomputer.com/imgdump/sample.png");
HttpResponseMessage response = await httpClient.SendAsync(request,
HttpCompletionOption.ResponseHeadersRead);
Uri imageUri;
BitmapImage image = null;
var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync(
"sample.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);
}
image1.Source = image;
}
大部分时间都可以使用,但出于某种原因,我有时会得到
UnauthorizedAccessException(0x80070005,E_ACCESSDENIED),HResult -2147024891。
因为错误是随机的并且通常有效,所以我不确定问题出在哪里。
任何帮助都将不胜感激。
答案 0 :(得分:0)
我最近遇到了同样的问题,经过一些测试我发现这是因为某些程序可能会在您尝试访问该文件时删除该文件。 这就是我进行测试的方式。
static void Main(string[] args)
{
Thread t1 = new Thread(Create);
Thread t2 = new Thread(Delete);
t1.Start();
t2.Start();
}
private static void Create()
{
int i = 0;
try
{
while (true)
{
System.IO.TextWriter writer = new System.IO.StreamWriter("file.txt");
i++;
System.Console.Out.WriteLine(i);
writer.Write(i);
writer.Close();
}
}
catch (System.UnauthorizedAccessException ex)
{
System.Console.Out.WriteLine("Boom at: " + i.ToString());
}
}
private static void Delete()
{
while (true)
{
try
{
System.IO.File.Delete("file.txt");
}
catch (UnauthorizedAccessException ex)
{
}
catch (Exception e)
{ }
}
}