gpt4 book ai didi

c# - 递归获取目录和文件?

转载 作者:行者123 更新时间:2023-11-30 22:20:33 25 4
gpt4 key购买 nike

可以递归获取所有目录、子目录和文件。

我这样做是因为我想增加我的编程逻辑,并了解递归的工作原理。

我知道用这种方式做到这一点:

 string path = "D://";
string rezdir,newpath;
DirectoryInfo di = new DirectoryInfo(path);
DirectoryInfo[] dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.WriteLine("\n\nChoose File: ");
rezdir = Console.ReadLine();
newpath = path + rezdir;
di = new DirectoryInfo(newpath);
dir = di.GetDirectories().ToArray();
for (int i = 0; i < di.GetDirectories().Length; i++)
{
Console.WriteLine(dir[i].ToString());
}
Console.ReadKey();

但我不会用递归的方式来做,所以如果有人能做到这一点,我将不胜感激。

最佳答案

按照您发布的代码 - 您似乎想要一些用户交互 - 所以尝试这样的事情:

 public static class RecursiveTest
{
public static string Foo(DirectoryInfo currentPath)
{
if (!currentPath.Exists) return string.Empty;

foreach (var directory in currentPath.EnumerateDirectories())
Console.WriteLine("Directory {0}", directory.Name);

foreach (var file in currentPath.EnumerateFiles())
Console.WriteLine("File {0}", file.Name);

while(true)
{
Console.WriteLine("Choose directory or file: ");
string chosenPath = Console.ReadLine();

string newPath = Path.Combine(currentPath.FullName, chosenPath);
if(Directory.Exists(newPath))
return Foo(new DirectoryInfo(newPath));

if(File.Exists(newPath))
return newPath;

Console.WriteLine("File {0} doesn't exist!", newPath);
}
}
}

然后用这样的方式调用:

class Program
{
static void Main(string[] args)
{
Console.WriteLine(RecursiveTest.Foo(new DirectoryInfo(@"d:\dev")));

Console.ReadLine();
}
}

HTH

关于c# - 递归获取目录和文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14921090/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com