CodeGo.net>如何列出硬盘驱动器上的所有文件和文件夹? [英] c# - How to list all files and folders on a hard drive?
本文介绍了CodeGo.net>如何列出硬盘驱动器上的所有文件和文件夹?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我想列出程序可以访问的所有文件和文件夹,并将它们写入文本文件.我将如何获得这份清单?我需要一种可以在无法访问的文件夹上捕获或不抛出UnauthorizedAccessExceptions的方法.
I want to list all files and folders that my program has access to and write them to a text file. How would I get the list? I need a way that will catch or not throw UnauthorizedAccessExceptions on folders that are not accessible.
推荐答案
请尝试使用以下代码:
private static IEnumerable<string> Traverse(string rootDirectory)
{
IEnumerable<string> files = Enumerable.Empty<string>();
IEnumerable<string> directories = Enumerable.Empty<string>();
try
{
// The test for UnauthorizedAccessException.
var permission = new FileIOPermission(FileIOPermissionAccess.PathDiscovery, rootDirectory);
permission.Demand();
files = Directory.GetFiles(rootDirectory);
directories = Directory.GetDirectories(rootDirectory);
}
catch
{
// Ignore folder (access denied).
rootDirectory = null;
}
if (rootDirectory != null)
yield return rootDirectory;
foreach (var file in files)
{
yield return file;
}
// Recursive call for SelectMany.
var subdirectoryItems = directories.SelectMany(Traverse);
foreach (var result in subdirectoryItems)
{
yield return result;
}
}
客户代码:
var paths = Traverse(@"Directory path");
File.WriteAllLines(@"File path for the list", paths);
这篇关于CodeGo.net>如何列出硬盘驱动器上的所有文件和文件夹?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文