Question

In my app I convert a bitmap to a png and store it in a file inside a folder. When I attempt to open the file again to write the second time I get an UnauthorisedAccessException saying the "Access is denied". When Save button is clicked, the following function is called.

private async void SaveClicked(object sender, RoutedEventArgs e)
        {
            WriteableBitmap wb = new WriteableBitmap(InkCanvas2, null);
            Image image = new Image();
            image.Height = 150;
            image.Width = 450;
            image.Source = wb;
            await SaveToStorage(wb, image);
            TransparentLayer.Visibility = System.Windows.Visibility.Collapsed;   

        }

The SaveToStorage has the following code

private async Task SaveToStorage(WriteableBitmap i, Image im)
        {
            try
            {    
                  var dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists);                    
                  using (var testpng = await dataFolder.OpenStreamForWriteAsync("testpng.png", CreationCollisionOption.ReplaceExisting)) 
// HITS EXCEPTION AND GOES TO CATCH BLOCK
                     {    
                       i.WritePNG(testpng);    
                       testpng.Flush();
                       testpng.Close();
                     }                    
            }  
            catch(Exception e)
            {
            string txt = e.Message;
            }
        }

It saves the first time with no error, the second time, throws exception. Any idea why this happens?

Was it helpful?

Solution

I figured out! It is apparently because I did not include a fileexist check before trying to open it.

I have re written the code like this

       IStorageFolder dataFolder = await local.CreateFolderAsync("Page", CreationCollisionOption.OpenIfExists);
            StorageFile Ink_File = null;
            //Using try catch to check if a file exists or not as there is no inbuilt function yet
            try
            {
                Ink_File = await dataFolder.GetFileAsync("testpng.png");
            }
            catch (FileNotFoundException)
            {
                return false;
            }

            try
            {
                if (Ink_File != null)
                {

                    using (var testpng = await Ink_File.OpenStreamForWriteAsync())
                    {

                        i.WritePNG(testpng);

                        testpng.Flush();
                        testpng.Close();
                        return true;
                    }
                }

            }
            catch(Exception e)
            {
                string txt = e.Message;
                return false;
            }
            return false;
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top