如何在 UWP 应用程序中创建文件夹?

How do I create a folder in a UWP application?

我在 运行 我的 UWP 应用程序时尝试创建。

我有以下代码:

string documentsPath = Package.Current.InstalledLocation.Path;
System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
Task.Factory.StartNew(async () =>
{
    await Package.Current.InstalledLocation.CreateFolderAsync("Data");
    mre.Set();
});
mre.WaitOne();

但是行:

await Package.Current.InstalledLocation.CreateFolderAsync("Data");

抛出以下错误:

"Access is denied. (Exception from HRESULT: 0x80070005 (E_ACCESSDENIED))"}

查看 this link: UWP File access permissions 内容如下:

When you create a new app, you can access the following file system locations by default:

Application install directory. The folder where your app is installed on the user’s system.

There are two primary ways to access files and folders in your app’s install directory:

You can retrieve a StorageFolder that represents your app's install directory, like this:

Windows.Storage.StorageFolder installedLocation = Windows.ApplicationModel.Package.Current.InstalledLocation

所以我认为我的代码可以工作。所以我的问题是如何使用 UWP 应用程序创建文件夹?

您无法在 InstalledLocation 中创建文件夹,MSDN:

...The app's install directory is a read-only location...

尝试改用本地文件夹:

ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");

使用ApplicationData.Current.LocalFolder.Path而不是Package.Current.InstalledLocation.Path

string documentsPath = ApplicationData.Current.LocalFolder.Path;

        System.Threading.ManualResetEvent mre = new System.Threading.ManualResetEvent(false);
        Task.Factory.StartNew(async () =>
        {
            await ApplicationData.Current.LocalFolder.CreateFolderAsync("Data");
            mre.Set();
        });
        mre.WaitOne();

Package.Current.InstalledLocation.Path 使用 visual studio 调试器为您提供所有代码和资源 运行 的路径,通常是源代码的调试文件夹。这无法通过 UWP API 库访问,而 UWP API 库通常在 .Net 应用程序 (win32) 中可用。

UWP 应用程序可以 read/write 访问文件夹“C:\Users\{userprofile}\AppData\Local\Packages\{packagenameguid}\” 您可以在应用程序运行时在此位置创建 folder/files。