获取将返回列表的文件夹和子文件夹中的所有文件的方法

编程入门 行业动态 更新时间:2024-10-08 04:28:40
本文介绍了获取将返回列表的文件夹和子文件夹中的所有文件的方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述 我有一个方法可以遍历文件夹及其所有子文件夹,并获取文件路径列表。但是,我只能弄清楚如何创建它,并将文件添加到公共列表,但不能返回列表。这是一个方法:

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.

更多推荐

获取将返回列表的文件夹和子文件夹中的所有文件的方法

本文发布于:2023-05-28 00:46:16,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/308218.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!