我想列出我的程序可以访问的所有文件和文件夹,并将它们写入文本文件。我怎么得到名单?我需要一种能够捕获或不捕获无法访问的文件夹上的UnauthorizedAccessExceptions的方法。
答案 0 :(得分:8)
请尝试使用代码:
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);
答案 1 :(得分:2)
尝试
string[] files = Directory.GetFiles(@"C:\\", "*.*", SearchOption.AllDirectories);
这会给你一个包含硬盘上所有文件的数组。
答案 2 :(得分:0)
查看Directory.GetFiles()
及相关方法。
答案 3 :(得分:0)
您可以尝试使用
var files = from file in Directory.EnumerateFiles(@"your Path", "*.*", SearchOption.AllDirectories)
select file;
答案 4 :(得分:0)
使用Serge建议的Traverse和DriveInfo类,您可以访问电脑可用的所有文件。
DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{
if (d.IsReady == true)
{
var paths = Traverse(d.Name);
File.AppendAllLines(@"File path for the list", paths);
}
}