方法获取文件夹和子文件夹,将返回一个列表中的所有文件 [英] Method to get all files within folder and subfolders that will return a list
问题描述
我有将通过一个夹迭代及其所有子文件夹的,并获得该文件的路径的列表的方法。但是,我只能找出如何创建它,将文件添加到一个公开名单,而不是如何返回列表。这里的方法:
公开名单<串GT;文件=新的List<串GT;();
私人无效DirSearch(字符串SDIR)
{
试
{
的foreach(串f在Directory.GetFiles(SDIR))
{
files.Add(F);
}
的foreach(在Directory.GetDirectories串D(SDIR))
{
DirSearch(D);
}
}
赶上(System.Exception的excpt)
{
MessageBox.Show(excpt.Message);
}
}
所以,我只是叫 DirSearch()
在我的代码中的一些点,它充满'的路径列表,但我希望能够用它多次创建具有不同的目录等不同的名单。
私人列表<串GT; DirSearch(字符串SDIR)
{
名单,LT;弦乐>文件=新的List<串GT;();
试
{
的foreach(串f在Directory.GetFiles(SDIR))
{
files.Add(F);
}
的foreach(在Directory.GetDirectories串D(SDIR))
{
files.AddRange(DirSearch(d)条);
}
}
赶上(System.Exception的excpt)
{
MessageBox.Show(excpt.Message);
}
返回文件;
}
如果你不希望加载在内存中的整个列表,并避免阻挡你可以看看在 以下的答案
。
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);
}
}
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屋!