Environment.GetFolderPath(Environment.SpecialFolder) 返回错误值
Environment.GetFolderPath(Environment.SpecialFolder) is returning wrong value
我有一个UWP项目,写了这段代码:
foreach (var foldertype in (Environment.SpecialFolder[])Enum.GetValues(typeof(Environment.SpecialFolder)))
{
//string d = Environment.CurrentDirectory;
var path = Environment.GetFolderPath(foldertype);
var folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageApplicationPermissions.FutureAccessList.Add(folder, folder.Path);
Debug.WriteLine($"Opened the folder: {folder.DisplayName}");
this.MenuFolderItems.Add(new MenuFolderItem(folder));
}
应该是枚举所有的特殊文件夹,得到它们的文件夹。但是,在调试时,会发生以下情况:
foldertype = Desktop
path = "C:\Users\cuent\AppData\Local\Packages\402b6149-1adf-4994-abc9-504111b3b972_a5s740xv383r0\LocalState\Desktop"
folder = [ERROR] System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
我不知道这里发生了什么,它似乎是将路径附加到应用程序的安装位置。我该如何解决这个问题?
GetFolderPath()
的预期输出是 Desktop
所在的位置,而不是奇怪的路径。
UWP 应用程序在访问文件系统时不同于桌面应用程序。 UWP 应用程序 运行 在沙盒中,因此 UWP 应用程序在尝试访问文件系统时存在限制。您可以查看此文档:File access permissions。该文档列出了 UWP 应用程序有权访问的所有位置。
回到您的场景,您首先需要的是 broadFileSystemAccess 受限功能。此功能使您的应用程序可以将 StorageFolder.GetFolderFromPathAsync()
API 与路径参数一起使用。这个在我上面贴的文档的最后一部分有提到。
那么第二期就是Environment.GetFolderPath
API。看起来 API 将 return 指向应用本地文件夹内的本地文件夹的路径。但是应用程序的本地文件夹中没有这样的桌面文件夹,因此您将得到 FileNotFoundException。您可能需要自己设置正确的路径,例如 C:\Users\your user name\Desktop
。之后,您的代码应该能够正常工作。
我有一个UWP项目,写了这段代码:
foreach (var foldertype in (Environment.SpecialFolder[])Enum.GetValues(typeof(Environment.SpecialFolder)))
{
//string d = Environment.CurrentDirectory;
var path = Environment.GetFolderPath(foldertype);
var folder = await StorageFolder.GetFolderFromPathAsync(path);
StorageApplicationPermissions.FutureAccessList.Add(folder, folder.Path);
Debug.WriteLine($"Opened the folder: {folder.DisplayName}");
this.MenuFolderItems.Add(new MenuFolderItem(folder));
}
应该是枚举所有的特殊文件夹,得到它们的文件夹。但是,在调试时,会发生以下情况:
foldertype = Desktop
path = "C:\Users\cuent\AppData\Local\Packages\402b6149-1adf-4994-abc9-504111b3b972_a5s740xv383r0\LocalState\Desktop"
folder = [ERROR] System.IO.FileNotFoundException: 'The system cannot find the file specified. (Exception from HRESULT: 0x80070002)'
我不知道这里发生了什么,它似乎是将路径附加到应用程序的安装位置。我该如何解决这个问题?
GetFolderPath()
的预期输出是 Desktop
所在的位置,而不是奇怪的路径。
UWP 应用程序在访问文件系统时不同于桌面应用程序。 UWP 应用程序 运行 在沙盒中,因此 UWP 应用程序在尝试访问文件系统时存在限制。您可以查看此文档:File access permissions。该文档列出了 UWP 应用程序有权访问的所有位置。
回到您的场景,您首先需要的是 broadFileSystemAccess 受限功能。此功能使您的应用程序可以将 StorageFolder.GetFolderFromPathAsync()
API 与路径参数一起使用。这个在我上面贴的文档的最后一部分有提到。
那么第二期就是Environment.GetFolderPath
API。看起来 API 将 return 指向应用本地文件夹内的本地文件夹的路径。但是应用程序的本地文件夹中没有这样的桌面文件夹,因此您将得到 FileNotFoundException。您可能需要自己设置正确的路径,例如 C:\Users\your user name\Desktop
。之后,您的代码应该能够正常工作。