如何使用c#?
在hardrive上获取所有目录(带子目录)回复示例:
C:\
C:\1
C:\2
C:\2\1
C:\2\1\4
C:\2\1\4\5
C:\2\1\4\5\6
C:\3
答案 0 :(得分:3)
using System.IO;
var directories = new List<string>(Directory.GetDirectories(@"c:\", "*", SearchOption.AllDirectories));
directories.ForEach(directory => Console.WriteLine(directory));
答案 1 :(得分:0)
贾斯汀的回答是100%有效的。如果这更像是学习技术而不是获得结果,那么你需要一个递归函数。所有这些意味着我们需要一个能够根据它返回的结果调用自身的函数。
public static void GetDirectories(string path, bool recursive)
{
Console.WriteLine(path); // write the name of the current directory
if (recursive) // if we want to get subdirectories
{
try // getting directories will throw an error if it is a path you don't have access to
{
foreach (var child in Directory.GetDirectories(path)) // get all the subdirectories for the given path
{
GetDirectories(child, recursive); // call our function for each sub directory
}
}
catch (UnauthorizedAccessException ex) // handle unauthorized access errors
{
Console.WriteLine(string.Format("You don't have permission to view subdirectories of {0}",path));
}
}
}
然后称之为:
static void Main(string[] args)
{
GetDirectories("c:\\", true);
Console.ReadLine();
}
再次,如果你只是想让列表与贾斯汀的答案一致,但这就是你自己做的方法。