microsoft / WindowsAppSDK

The Windows App SDK empowers all Windows desktop apps with modern Windows UI, APIs, and platform features, including back-compat support, shipped via NuGet.
https://docs.microsoft.com/windows/apps/windows-app-sdk/
MIT License
3.79k stars 320 forks source link

ApplicationData API not working for unpackaged app #1721

Closed mpo-dev closed 2 years ago

mpo-dev commented 2 years ago

Describe the bug

Accessing the ApplicationData API on an unpackaged app causes an System.InvalidOperationException to be thrown.

Steps to reproduce the bug

  1. Create a new WinUI 3 unpackaged desktop app.
  2. Access the ApplicationData API
    var applicationData = Windows.Storage.ApplicationData.Current;

Expected behavior

No response

Screenshots

No response

IDE

Visual Studio 2019

NuGet package version

Microsoft.WindowsAppSDK 1.0.0-preview3

Project type

Windows version

Windows 11 (22000)

Additional context

No response

roxk commented 2 years ago

As per the list of API that requires package identity, ApplicationData isn't supported for unpackaged app. You might want to manually grab the AppData folder path instead.

I'm no expert on this and binging pointed me to SHGetKnownFolderPath .

andrewleader commented 2 years ago

Correct, the ApplicationData APIs aren't supported by unpackaged apps.

Unpackaged apps can store app data in traditional ways, like the AppData folder as roxk suggested. You then need to pick a unique folder within there, so probably something like [Publisher][AppName], for example in my apps I'd store my files in AppData\Local\BareBonesDev.PowerPlanner.

In C#, you can use Environment.GetFolderPath to get the folder path of the AppData folder, as described in https://stackoverflow.com/a/9659171

You'll want to place it in the local AppData folder (AppData\Local) unless you want the app data to roam across the user's Windows devices.

To experiment and view this AppData folder within File Explorer, open File Explorer and in the address bar, simply enter `%localappdata% and press enter, and that'll take you to your app data folder for your current account, and you can see how other apps on your computer utilize that folder.

If you would like a single AppData API that works the same for unpackaged and packaged apps, you can let us know by opening a new separate feature request. Thanks!

dotMorten commented 2 years ago

@andrewleader The problem with the AppData folder is, it is the same for all apps - you easily risk one app overwriting a different apps' data - sure you can use folders below it (and should) but it's harder to do for class libraries, and there's no guaranteed the data gets removed once the app is removed.