获取将返回列表的文件夹和子文件夹中所有文件的方法 [英] Method to get all files within folder and subfolders that will return a list
问题描述
我有一个方法可以遍历文件夹及其所有子文件夹并获取文件路径列表.但是,我只能弄清楚如何创建它并将文件添加到公共列表中,而不能弄清楚如何返回列表.方法如下:
I have a method that will iterate through a folder and all of its subfolders and get a list of the file paths. However, I could only figure out how to create it and add the files to a public List, but not how to return the list. Here's the method:
public List<String> files = new List<String>();
private void DirSearch(string sDir)
{
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
DirSearch(d);
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
}
所以,我只是在代码中的某个点调用 DirSearch()
并用路径填充"列表,但我希望能够多次使用它来创建不同的列表具有不同的目录等
So, i just call DirSearch()
at some point in my code and it 'fills' the list with the paths, but I want to be able to use it multiple times to create different lists with different directories, etc.
推荐答案
private List<String> DirSearch(string sDir)
{
List<String> files = new List<String>();
try
{
foreach (string f in Directory.GetFiles(sDir))
{
files.Add(f);
}
foreach (string d in Directory.GetDirectories(sDir))
{
files.AddRange(DirSearch(d));
}
}
catch (System.Exception excpt)
{
MessageBox.Show(excpt.Message);
}
return files;
}
如果您不想在内存中加载整个列表并避免阻塞,您可以查看以下答案
.
and if you don't want to load the entire list in memory and avoid blocking you may take a look at the following answer
.
这篇关于获取将返回列表的文件夹和子文件夹中所有文件的方法的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!