1、定义变量
增加using
System.Windows.Forms
/// <summary>
/// 私有变量
/// </summary>
private static List<FileInfo> lst = new List<FileInfo>();
2、获取文件路径
public string GetPath()
{
FolderBrowserDialog path = new FolderBrowserDialog();
OpenFileDialog openFileDialog1 = new OpenFileDialog();
//指定路径
openFileDialog1.InitialDirectory = @"D:\";
openFileDialog1.Filter = "All Files|*.*";
if (path.ShowDialog() == System.Windows.Forms.DialogResult.OK)
{
return path.SelectedPath;
}
else
{
return string.Empty;
}
}
3、 递归获取文件信息
/// <summary>
/// 递归获取指定类型文件,包含子文件夹,参数一是路径,参数二是需要筛选文件的扩展名
/// 扩展名可以多个 例如 .mp3.wma.rm
/// </summary>
/// <param name="path"></param>
/// <param name="extName"></param>
private void getdir(string path, string extName)
{
try
{
string[] dir = Directory.GetDirectories(path); //文件夹列表
DirectoryInfo fdir = new DirectoryInfo(path);
FileInfo[] file = fdir.GetFiles();//该目录下所有文件的各种信息的集合
// List<string> file2 = Directory.GetFiles(path).ToList(); //文件路径列表
if (file.Length != 0 || dir.Length != 0) //当前目录文件或文件夹不为空
{
foreach (FileInfo f in file) //显示当前目录所有文件
{
if (extName.ToLower().IndexOf("*.*") >= 0)
{
lst.Add(f);
}
else if (extName.ToLower().IndexOf(f.Extension.ToLower()) >= 0)
{
lst.Add(f);
}
}
foreach (string d in dir)
{
getdir(d, extName);//递归
}
}
}
catch (Exception ex)
{
Console.Write(ex.Message);
}
}
4、调用
比如要筛选指定文件夹下所有的TXT文件
private void Button_Click_2(object sender, RoutedEventArgs e)
{
getdir(GetPath(), ".txt");
}