遍历文件夹 DirectoryInfo类
该类有三个方法:
GetDirectories() 当前目录的子目录
GetFiles() 当前目录的文件列表
GetFileSystemInfos() 当前目录的文件、子目录,返回强类型FileSystemInfo数组
private void button1_Click(object sender, EventArgs e) { listView1.Items.Clear(); //清空列表 if (folderBrowserDialog1.ShowDialog()==DialogResult.OK) { textBox1.Text = folderBrowserDialog1.SelectedPath; //选中的路径 DirectoryInfo info = new DirectoryInfo(textBox1.Text); FileSystemInfo[] fsInfo = info.GetFileSystemInfos();//获取该目录的文件、子目录 foreach (FileSystemInfo f in fsInfo) { if (f is DirectoryInfo)//如果是子目录 { DirectoryInfo dir = new DirectoryInfo(f.FullName); listView1.Items.Add(dir.Name); //第一列展示 //listView1.Items[listView1.Items.Count - 1].SubItems.Add(dir.FullName); //第二列展示 listView1.Items[1].SubItems.Add(dir.FullName); //等效 } else //如果是文件 { FileInfo file = new FileInfo(f.FullName); listView1.Items.Add(file.Name); listView1.Items[listView1.Items.Count-1].SubItems.Add(file.FullName); } } } }