SpecialFolder.ApplicationData not working in .net MAUI?

2.1k Views Asked by At

I cannot get my directories made to AppData/Roaming while using this code in .net MAUI:

        RootLocation = new DirectoryInfo(GetFolderPath(SpecialFolder.ApplicationData) + "/MyApp");
        SaveLocation = new DirectoryInfo(RootLocation.FullName + "/saves");
        SaveLocation.Create();
        BackupLocation = new DirectoryInfo(RootLocation.FullName + "/backups");
        BackupLocation.Create();

However if I change SpecialFolder.ApplicationData to SpecialFolder.Desktop it does work on Desktop. It seems to be a permissions issue however in Visual Studio 2019 using WPF I can still save to AppData/Roaming. Could this be an issue with Visual Studio 2022 Preview?

2

There are 2 best solutions below

0
JohnSteve On BEST ANSWER
if (IsWindows())
{
    savingPath = Environment.GetFolderPath(Environment.SpecialFolder.MyVideos);
    savingPath = Path.Combine(savingPath, "yourfolder");
    if (!Directory.Exists(savingPath))
    {
        Directory.CreateDirectory(savingPath);
    }
}

I think it will be better. And the code is running correctly on my desktop and my Android app

0
James On

By default, Maui apps are not allowed to access SpecialFolder.ApplicationData in the normal location. This is because of app virtualization and containerization.

Maui compiles on Windows as a WinUI3 appx/msix. It's configured with special "file system virtualization" that changes where files are written. In particular, when you try to write to C:\Users\username\AppData\Roaming it instead writes to C:\Users\username\AppData\Local\Packages\package_id\LocalCache\Roaming or some variant in the Packages directory. The justification for this is it allows the uninstaller to completely remove all of the app's resources.

Fortunately, the virtualization can be disabled by adding the following to your project's Platforms\Windows\Package.appxmanifest:

<Package
 ...
 xmlns:desktop6="http://schemas.microsoft.com/appx/manifest/desktop/windows10/6"
 xmlns:rescap="http://schemas.microsoft.com/appx/manifest/foundation/windows10/restrictedcapabilities"
 IgnorableNamespaces="... rescap">

  <Properties>
    ...
    <desktop6:FileSystemWriteVirtualization>disabled</desktop6:FileSystemWriteVirtualization>
  </Properties>

  <Capabilities>
    ...
    <rescap:Capability Name="unvirtualizedResources"/>