我遇到一个奇怪的问题,在测试我的应用程序时,我可以使用 WinRT API 将 System.Drawing.Bitmap 保存到 StorageFile,但是当安装应用程序时,它不起作用。
这是有问题的代码。
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();
知道为什么安装时会失败但从 VS2022 运行时工作正常(调试和发布模式)吗?
我尝试了默认的 Bitmap.Save(directory/stream) 但这也不起作用(以同样的方式失败)。
这是尝试保存位图时抛出的异常:
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)