功能需求:类资源管理器的功能,选择一个路径,然后得到路径下的目录结构,返回的是一个列表
一、封装的函数
基本思想:主要是一个递归,判断object类型是文件还是文件夹,然后再放入发入对应的集合中
/// <summary>
/// 220305 komla
/// </summary>
/// <param name="list"></param>
/// <param name="path"></param>
/// <returns></returns>
private static List<DirInfo> ListDirectory(List<DirInfo> list,string path)
{
DirectoryInfo folder = new DirectoryInfo(@path);
//遍历文件
foreach (FileInfo NextFile in folder.GetFiles())
{
//Console.WriteLine(path + NextFile.Name + "\r\n");
//richTextBox1.AppendText(path + NextFile.Name + "\r\n");//文件路径
list.Add(new DirInfo
{
FileName = NextFile.Name,
//state = new state { opened = false },
});
}
//遍历文件夹
foreach (DirectoryInfo NextFolder in folder.GetDirectories())
{
list.Add(new DirInfo
{
DirName = NextFolder.Name,
DirChildren = ListDirectory(new List<DirInfo>(), NextFolder.FullName)
});
//ListDirectory(new List<FileNames>(), NextFolder.FullName);
}
return list;
}
二、类
public class DirInfo
{
public DirInfo()
{
DirChildren = new List<DirInfo>();
}
public string DirName { get; set; }
public string FileName { get; set; }
public List<DirInfo> DirChildren { get; set; }
}
说明:大家可以根据自己需求写这个类,比如文件类型了,文件大小了等