遍历指定目录下的所有文件
完整代码如下:
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
/// <summary>
/// 遍历路径
/// </summary>
/// <param name="info"></param>
private void ListPath(FileSystemInfo info)
{
if (!info.Exists) return;
DirectoryInfo dir = info as DirectoryInfo;
if (dir == null) return; //不是目录
FileSystemInfo[] files = dir.GetFileSystemInfos();
for (int i = 0; i < files.Length; i++)
{
FileInfo file = files[i] as FileInfo;
if (file != null)
{
textBox1.Text += $"{file.DirectoryName}\\{file.Name}\r\n";
}
else ListPath(files[i]);
}
}
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog dialog = new FolderBrowserDialog();
dialog.Description = "请选择文件路径";
if (dialog.ShowDialog() == DialogResult.OK)
{
ListPath(new DirectoryInfo(dialog.SelectedPath));
}
}
}
}