本文介绍了获取将返回列表的文件夹和子文件夹中的所有文件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个方法可以遍历文件夹及其所有子文件夹,并获取文件路径列表。但是,我只能弄清楚如何创建它,并将文件添加到公共列表,但不能返回列表。这是一个方法: public List< String> files = new List< String>(); private void DirSearch(string sDir) { try { foreach(Directory.GetFiles(sDir)中的字符串f) { files.Add(f); } foreach(Directory.GetDirectories(sDir)中的字符串d) { DirSearch(d); } } catch(System.Exception excpt) { MessageBox.Show(excpt.Message); } }
所以,我只需调用 DirSearch()在我的代码的某一点,它'填充'列表与路径,但我想要能够使用它多次创建不同的列表与不同的目录等。 p>
解决方案private List< String> DirSearch(string sDir) {列表< String> files = new List< String>(); 尝试 { foreach(Directory.GetFiles(sDir)中的字符串f) { files.Add(f); } foreach(Directory.GetDirectories(sDir)中的字符串d) { files.AddRange(DirSearch(d)); } } catch(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.
更多推荐
获取将返回列表的文件夹和子文件夹中的所有文件的方法
发布评论