在Windows 10通用应用程序UWP中创建新目录

本文关键字:创建 新目录 UWP 应用程序 Windows 10通 | 更新日期: 2023-09-27 18:10:11

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

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

在Windows 10通用应用程序UWP中创建新目录

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

试试这个:

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

Try This

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

每个应用程序在一个特定的用户下运行,并继承它的特权,权限,限制和…所以运行应用程序的用户,没有足够的权限,无法创建文件夹所以你可以:

  • 使用Impersonation(查找Impersonation c#)并将您的应用程序作为具有所需权限的另一个用户(如管理员)运行。之后,您的应用程序始终自动以管理员(或特定用户)身份运行。(如果你冒充你的应用作为管理员,注意安全问题)
  • 以管理员(或具有足够权限的用户)手动运行应用程序。(对于管理员,右键单击your-app.exe,然后单击"运行为…")
  • 更改您的工作目录的安全设置和访问限制(例如C:'Users[username]'Documents'MyApp'bin'x86'Debug'AppX'newFolder),并给写权限到您的用户名

以管理员权限运行您的应用程序,应该可以完成。