这几天,陆续都遇见了几个关于遍历指定路径的子目录和文件的问题.就查询整理了一个关于目录和文件操作的小例子.
这个例子是用winform做的,我只贴出cs代码:
using System; using System.Windows.Forms; using System.IO; using System.Collections; namespace 遍历目录 { public partial class Form1 : Form { public Form1() { InitializeComponent(); } public ArrayList al = new ArrayList(); private void button1_Click(object sender, EventArgs e) { //声明一个选择路径的对话框 FolderBrowserDialog folder = new FolderBrowserDialog(); //打开对话框 DialogResult sfDia = folder.ShowDialog(); if (sfDia != DialogResult.Cancel) { //获取选择的文件夹路径 string selPath = folder.SelectedPath; //先清空集合中 的所有元素 al.Clear(); GetAllDirList(selPath); //把所有目录信息从ArrayList中读取出来 listBox1.Items.Clear(); for (int i = 0; i < al.Count; i++) { listBox1.Items.Add(al[i].ToString()); } } } private void button2_Click(object sender, EventArgs e) { #region 参考代码 ////声明一个打开文件的对话框 //OpenFileDialog opFile = new OpenFileDialog(); ////打开对话框 //DialogResult sfile = opFile.ShowDialog(); ////获取文件的绝对路径 //string filePath = opFile.FileName; ////获取扩展名 //string extendName = Path.GetExtension(filePath); ////获取文件名 //string docName = Path.GetFileName(filePath); #endregion //声明一个选择路径的对话框 FolderBrowserDialog folder = new FolderBrowserDialog(); //打开对话框 DialogResult sfDia = folder.ShowDialog(); if (sfDia != DialogResult.Cancel) { //获取选择的文件夹路径 string selPath = folder.SelectedPath; GetAllFileInfoList(selPath); //把所有目录信息从ArrayList中读取出来 listBox1.Items.Clear(); for (int i = 0; i < al.Count; i++) { listBox1.Items.Add(al[i].ToString()); } } } /// <summary> /// 递归获取指定目录的的所有子目录 /// </summary> /// <param name="strBaseDir"></param> public void GetAllDirList(string strBaseDir) { DirectoryInfo di = new DirectoryInfo(strBaseDir); DirectoryInfo[] diA = null; try { diA = di.GetDirectories(); } catch (Exception ex) { listBox1.Items.Add(ex.Message); } if (diA != null) { for (int i = 0; i < diA.Length; i++) { al.Add(diA[i].FullName); //diA[i].FullName是某个子目录的绝对地址,把它记录在ArrayList中 GetAllDirList(diA[i].FullName); //注意:递归了. } } } /// <summary> /// 获取指定路径下所有文件信息 /// </summary> /// <param name="strBaseDir"></param> public void GetAllFileInfoList(string strBaseDir) { DirectoryInfo di = new DirectoryInfo(strBaseDir); FileInfo[] diA = null; try { diA = di.GetFiles(); } catch (Exception ex) { listBox1.Items.Add(ex.Message); } if (diA != null) { //先清空集合中 的所有元素 al.Clear(); for (int i = 0; i < diA.Length; i++) { al.Add(diA[i].FullName); //diA[i].FullName是某个子目录的绝对地址,把它记录在ArrayList中 } } } } }