0

我有以下代码从我的 Windows 8 应用程序中的网络服务器获取动态图像。

        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。

因为错误是随机的并且它通常有效,所以我不确定问题出在哪里。

任何帮助,将不胜感激。

4

1 回答 1

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

    }
于 2013-11-05T01:57:29.937 回答