简体   繁体   中英

CreateFileAsync UnauthorizedAccessException

I have the following code that fetches a dynamic image from a webserver in my Windows 8 app.

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

This works most of the time, but for some reason there are times where I get an

UnauthorizedAccessException (0x80070005, E_ACCESSDENIED), HResult -2147024891.

Because the errors are random and it usually works, I'm not sure where the problem lies.

Any help would be appreciated.

I have the same issue recently, after some test I find that it's because some programs may be deleting the file while you try to access it. Here's how I did the test.

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

    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM