首先在MetroWindow里面拖一个按钮,用于弹出选择文件夹的对话框,再拖一个dataGrid数据控件,方便显示读取出来的文件列表
把下面的代码copy进去运行吧
using System;结果如下图:
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using MahApps.Metro.Controls;
using System.Data;
namespace WpfApp1
{
/// <summary>
/// Interaction logic for MainWindow.xaml
/// </summary>
public partial class MainWindow : MetroWindow
{
public MainWindow()
{
InitializeComponent();
}
private void button_Click(object sender, RoutedEventArgs e)
{
System.Windows.Forms.FolderBrowserDialog openFileDialog = new System.Windows.Forms.FolderBrowserDialog(); //选择文件夹
if (openFileDialog.ShowDialog() == System.Windows.Forms.DialogResult.OK)//注意,此处一定要手动引入System.Window.Forms空间,否则你如果使用默认的DialogResult会发现没有OK属性
{
dataGrid.ItemsSource = GetFile(openFileDialog.SelectedPath,new List<filelist>());
}
}
private List<filelist> GetFile(string Sdir, List<filelist> list)
{
DirectoryInfo dir = new DirectoryInfo(Sdir);
try
{
//判断所指的文件夹/文件是否存在
if (!dir.Exists)
return null;
DirectoryInfo dirD = dir as DirectoryInfo;
FileSystemInfo[] files = dirD.GetFileSystemInfos();//获取文件夹下所有文件和文件夹
//对单个FileSystemInfo进行判断,如果是文件夹则进行递归操作
foreach (FileSystemInfo FSys in files)
{
FileInfo fileInfo = FSys as FileInfo;
if (fileInfo != null)
{
//如果是文件,进行文件操作
FileInfo SFInfo = new FileInfo(fileInfo.DirectoryName + "\\" + fileInfo.Name);//获取文件所在原始路径
filelist row = new filelist();
row.filename = SFInfo.Name;
row.createtime = SFInfo.CreationTime;
row.path = SFInfo.FullName;
list.Add(row);
}
else
{
//如果是文件夹,则进行递归调用
string pp = FSys.Name;
GetFile(Sdir + "\\" + pp, list);
}
}
return list;
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
return null;
}
}
}
public class filelist {
public string filename { get; set; }
public DateTime createtime { get; set; }
public string path { get; set; }
}
}
- 本文标题: WPF如何遍历循环文件夹里面的每个文件返回文件列表
- 文章分类:【WinForm/WPF】
- 非特殊说明,本文版权归【胡同里的砖头】个人博客 所有,转载请注明出处.