我正在开发一个Windows 10 UWP应用程序,无论何时运行以下代码,我都会得到以下执行:
' UnauthorizedAccessException - 拒绝访问路径{路径名}'。
我尝试了几个Windows文件夹(路径):
这是我的代码:
public async Task GetFiles() // edit added wrapper method for readability
{
var filePicker = new FileOpenPicker();
filePicker.FileTypeFilter.Add("*");
Windows.Storage.StorageFile file = await filePicker.PickSingleFileAsync();
if (file != null)
{
ChosenFiles.ItemsSource = GetFileInfo(file.Path);
}
}
public List<string> GetFileInfo(string path)
{
List<string> files = new List<string>();
string[] allFiles = Directory.GetFiles(path);
foreach (var file in allFiles)
{
FileInfo Info = new FileInfo(file);
files.Add(Info.Name);
}
return files;
}
答案 0 :(得分:1)
System.IO.Directory似乎只能直接访问应用包和应用本地存储文件夹。这意味着您应该使用StorageFile和StorageFolder类来提取所需的信息。例如:
private async void ButtonBase_OnClick(object sender, RoutedEventArgs args)
{
var folderPicker = new FolderPicker();
var folder = await folderPicker.PickSingleFolderAsync();
if (folder != null)
{
ChosenFiles.ItemsSource = await GetFileInfoAsync(folder);
}
}
public async Task<List<string>> GetFileInfoAsync(StorageFolder folder)
{
List<string> files = new List<string>();
var allFiles = await folder.GetFilesAsync();
foreach (var file in allFiles)
{
files.Add(file.Name);
}
return files;
}
请注意,如果您选择了一个文件,则无法枚举其邻居,因为您无权访问其父文件夹。因此,对于您的场景,您应该使用FolderPicker。