最近因为项目需要,昨天写了个递归算法获取文件夹及其子文件夹的文件信息,记录下,希望对大家有用
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 |
class Program { static void Main(string[] args) { Folder objFolder = getAllDirectories(@"\\cpp-PC\testa"); } //--递归算法获取文件夹及其子文件夹的文件信息 protected static Folder getAllDirectories(string rootPath) { Folder objFolder = new Folder(); DirectoryInfo TheFolder = new DirectoryInfo(rootPath); FileSystemInfo[] files = TheFolder.GetFileSystemInfos(); List<file> lstFile = new List<file>(); List<Folder> lstFolder = new List<Folder>(); foreach (FileSystemInfo item in files) { if (item.Attributes.ToString() == "Directory") { lstFolder.Add(getAllDirectories(item.FullName)); } else { lstFile.Add(new file { FileName = item.Name, FileDate = item.LastWriteTime.ToString("yyyy-MM-dd hh:mm:ss") }); } } objFolder.FolderName = rootPath; objFolder.files = lstFile; objFolder.folders = lstFolder; return objFolder; } } public class file { public string FileName { get; set; } public string FileDate { get; set; } } public class Folder { public string FolderName { get; set; } public List<file> files { get; set; } public List<Folder> folders { get; set; } } |