I am having a strange issue where I am able to save a System.Drawing.Bitmap to a StorageFile using WinRT APIs when testing my app, but when the app is installed it does not work.
Here is the code in question.
StorageFolder historyFolder = await ApplicationData.Current.LocalFolder.CreateFolderAsync("history", CreationCollisionOption.OpenIfExists);
StorageFile imageFile = await historyFolder.CreateFileAsync(filename, CreationCollisionOption.ReplaceExisting);
using var stream = new MemoryStream();
image.Save(stream, ImageFormat.Png);
byte[] byteArray = stream.ToArray();
using var randomAccessStream = await imageFile.OpenAsync(FileAccessMode.ReadWrite);
using var outputStream = randomAccessStream.GetOutputStreamAt(0);
using var dataWriter = new DataWriter(outputStream);
dataWriter.WriteBytes(byteArray);
await dataWriter.StoreAsync();
dataWriter.DetachStream();
await outputStream.FlushAsync();
Any idea why this would fail when installed but work fine when running from VS2022 (debug and release mode)?
I have tried the default Bitmap.Save(directory/stream) but that doesn't work either (fails in the same way).
This is the exception thrown when trying to save the Bitmap:
Unhandled exception: System.UnauthorizedAccessException: Access to the path 'C:\Program Files\WindowsApps\40087JoeFinApps.TextGrab_4.1.3.0_x64__kdbpvth5scec4\Text-Grab\history' is denied.
at System.IO.FileSystem.CreateDirectory(String fullPath, Byte[] securityDescriptor)
at System.IO.Directory.CreateDirectory(String path)
at Text_Grab.Services.HistoryService.SaveToHistory(HistoryInfo infoFromFullscreenGrab)
at Text_Grab.Views.FullscreenGrab.RegionClickCanvas_MouseUp(Object sender, MouseButtonEventArgs e)
at System.Threading.Tasks.Task.<>c.<ThrowAsync>b__128_0(Object state)
at System.Windows.Threading.ExceptionWrapper.InternalRealCall(Delegate callback, Object args, Int32 numArgs)
at System.Windows.Threading.ExceptionWrapper.TryCatchWhen(Object source, Delegate callback, Object args, Int32 numArgs, Delegate catchHandler)
Because the unpackaged application lacks package identity, it does not support the
Windows.StorageAPI.It is recommended that you use System.IO.File to handle storage in unpackaged app.