选择文件夹,获取文件夹里的所有文件
点击文本框,选择文件夹,点击确定
下面我们用代码来实现:
首先,我们写一个函数,用递归的方法实现循环遍历,找到文件夹里所有的文件(此处以xml为例)
private static List<string> ReplaceTextInRecursiveDir(string path, bool bSearchChildDir) { DirectoryInfo di = new DirectoryInfo(path); FileInfo[] files = di.GetFiles("*.xml"); foreach (FileInfo file in files) { if (!file.Name.Contains("$")) { fileList.Add(file.FullName); } } if (bSearchChildDir == true) { DirectoryInfo[] dirs = di.GetDirectories(); foreach (DirectoryInfo dir in dirs) { ReplaceTextInRecursiveDir(dir.FullName, bSearchChildDir); } } return fileList; }
创建文本框的点击事件
private void textBox1_Click(object sender, EventArgs e) { FolderBrowserDialog dialog = new FolderBrowserDialog(); dialog.Description = "请选择你要操作的文件夹"; if (dialog.ShowDialog() == DialogResult.OK) { if (string.IsNullOrEmpty(dialog.SelectedPath)) { MessageBox.Show(this, "文件夹路径不能为空", "提示"); return; } //把路径写在文本框上 textBox1.Text = dialog.SelectedPath; fileList = ReplaceTextInRecursiveDir(dialog.SelectedPath, true); } }
上段代码中 fileList 是一个static变量
static List<string> fileList = new List<string>();
老铁,希望可以帮到!!!