UnauthorizedAccessException while saving file

I have the following code in a Windows 8 C # application that retrieves an image from a server and saves it:

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

It looks like I accidentally get errors on this particular line:

  var imageFile = await ApplicationData.Current.LocalFolder.CreateFileAsync( "test.png", CreationCollisionOption.ReplaceExisting); 

This does not always happen, so I'm not sure how to identify the problem. All error data is given here:

Authentication failedAccessException

Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED)) in System.Runtime.CompilerServices.TaskAwaiter.ThrowForNonSuccess (Task tasks) under System.Runtime.CompilerServices.TaskAwaiter.HandleNonSuccessAndDebuggerRoter.task.CommentationTot.Commenter () in TestApp.MainPage.d__4.MoveNext () in d: \ TestApp \ TestApp \ MainPage.xaml.cs: line 86

+6
source share
3 answers

Update. Access Denied errors are caused by several things.

The first reason is related to image upload. Something in the downloadable code seems to be holding an open file. I have simplified the download code below.

The second reason is related to the BitmapImage object holding the file. See This Post for more information: Access is denied when deleting an image file previously used in the DataTemplate in WinRT

One way to solve the second problem is to use stream instead of Uri to initialize BitmapImage .

Here is the version that works for me (your source code is also here, but commented out):

 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); } */ var fs = await imageFile.OpenStreamForWriteAsync(); await response.Content.CopyToAsync(fs); await fs.FlushAsync(); // you may want to have this Dispose as part of a // finally block (try/ catch/ finally) fs.Dispose(); var bs = await imageFile.OpenAsync(Windows.Storage.FileAccessMode.Read); image = new BitmapImage(); image.SetSource(bs); ... image1.Source = image; 
+6
source

I had the same problem when I loaded a PDF into a LocalFolder file and tried to display it. I can’t say exactly why this is happening, but this little hack helped me solve this problem:

Instead of using

 try { StorageFile storage = await ApplicationData.Current.LocalFolder.CreateFileAsync( fileName, CreationCollisionOption.ReplaceIfExists); //work with file } catch (Exception) { ... } 

Now I use this:

 StorageFile storage = null; try { //First try to get the file storage = await ApplicationData.Current.LocalFolder.GetFileAsync(fileName); } catch (Exception) { //Ignore this exception } try { //If the storage file is still null, create it if (storage == null) storage = await ApplicationData.Current.LocalFolder.CreateFileAsync( fileName, CreationCollisionOption.OpenIfExists); //Work with file } catch (Exception) { //Process exception } 
+1
source

If you have the opportunity to use CreationCollisionOption. GenerateUniqueName instead of ReplaceExisting, try using this.

At least he solved the problem for me.

+1
source

Source: https://habr.com/ru/post/946853/


All Articles