在 Windows 10 Universal App UWP 中创建新目录

Creating a new directory in a Windows 10 Universal App UWP

我正在尝试使用此方法创建一个目录,该方法在应用程序中按下按钮后触发,并向其中添加一个文件:

DirectoryInfo d = new DirectoryInfo(@"..\newFolder\");
FileInfo f = new FileInfo(@"..\newFolder\foo.txt");
if (!d.Exists)
{
    d.Create();
}
if (!f.Exists)
{
    f.Create().Dispose();
}

这是我的通用应用程序因执行此操作而产生的错误:

An exception of type 'System.UnauthorizedAccessException' 
occurred in System.IO.FileSystem.dll but was not handled in user code

Additional information: Access to the path
 'C:\Users\[username]\Documents\MyApp\bin\x86\Debug\AppX\newFolder' is denied.

是否有人熟悉此错误或知道任何建议?

编辑 除了以下内容之外,这是在 Windows 10 通用应用程序环境中使用文件系统的重要资源:文件访问和权限(Windows 运行时应用程序)https://msdn.microsoft.com/en-us/library/windows/apps/xaml/Hh758325.aspx

运行 您的应用程序具有管理权限,应该完成。

每个应用程序都在(由)特定用户下运行,并继承其特权、权限、限制和... 所以 您的应用程序在其下运行的用户没有足够的权限,无法创建文件夹 所以你可以:

  • 使用模拟(搜索模拟 c#)并将您的应用程序编码为以具有所需权限的另一个用户(如管理员)身份运行。之后,您的应用程序始终自动以管理员(或特定用户)身份运行。 (如果您以管理员身份模拟您的应用,请注意安全问题)
  • 运行 您以管理员身份(或具有足够权限的用户)手动申请。 (对于管理员,右键单击您的-app.exe 并单击 "Run as ...")
  • 更改您的工作目录(例如 C:\Users[用户名]\Documents\MyApp\bin\x86\Debug\AppX\newFolder)的安全设置和访问限制,并为您的用户名[=19]授予写入权限 =]

问题是您正试图在应用程序的安装文件夹中创建一个文件,而通用应用程序不允许这样做。您只能在本地数据文件夹中创建文件夹。

试试这个:

using Windows.Storage;

var localRoot = ApplicationData.Current.LocalFolder.Path;
DirectoryInfo d = new DirectoryInfo(localRoot + "\test");
if (!d.Exists)
  d.Create();

试试这个

public static async void  WriteTrace()
{
  StorageFolder localFolder = ApplicationData.Current.LocalFolder;
  StorageFolder LogFolder = await localFolder.CreateFolderAsync("LogFiles", CreationCollisionOption.OpenIfExists);
 }