简体   繁体   中英

Windows Store C#: System.UnauthorizedAccessException writing image file

I'm currently creating a Windows store app (C#) that pulls an image from a URL at a regular interval (every 3 seconds) and displays it on a page. The image is successfully downloaded to temporary app storage once, but I get an Access denied (UnauthorizedAccessException) the second time round.

This is most likely because my app is using the file as a source for a bitmap (so it's still open) when it tries to overwrite it with a new image.

Is there a workaround for this that avoids the concurrency problem?

public async void GetLocalImageAsync(string internetUri, string uniqueName)
   {
       //Set up the web request and pass credentials.
       HttpWebRequest request = (HttpWebRequest)WebRequest.Create(internetUri);
      request.Credentials = new NetworkCredential("james", "jam3s");
        //get response
          using (var response = await request.GetResponseAsync())
          {
              using (var stream = response.GetResponseStream())
              {
                  var desiredName = string.Format(uniqueName);
                  //create the file.
                  var file = await ApplicationData.Current.TemporaryFolder.CreateFileAsync(desiredName, CreationCollisionOption.ReplaceExisting);

                  using (var filestream = await file.OpenStreamForWriteAsync())
                  {
                      await stream.CopyToAsync(filestream);

                      //update the bitmap image with the file we just downloaded.
                      BitmapImage c1src = new BitmapImage(new Uri("ms-appdata:///temp/camera1imgsrc.png"));
                      camera1img.Source = c1src;

                  }
              }
          }


   }

You could store each downloaded file with a different name (eg by adding a timestamp or sequential number to the root file name). After you download it, you can set the source to this new downloaded file and delete the previous one after that.

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