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?
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