private static void FillDirectoryTree(string folderName) { rootFolder = new Folder(folderName); System.IO.DriveInfo di = new System.IO.DriveInfo("C"); // Here we skip the drive if it is not ready to be read. This // is not necessarily the appropriate action in all scenarios. System.IO.DirectoryInfo rootDir = di.RootDirectory; WalkDirectoryTree(rootDir.GetDirectories("WINDOWS").FirstOrDefault(), rootFolder); rootFolder = rootFolder.Folders.FirstOrDefault(); }
static void WalkDirectoryTree(System.IO.DirectoryInfo root, Folder folder) { System.IO.FileInfo[] files = null; System.IO.DirectoryInfo[] subDirs = null; Folder newFolder = new Folder(root.Name); // First, process all the files directly under this folder try { files = root.GetFiles("*.*"); } // This is thrown if even one of the files requires permissions greater // than the application provides. catch (UnauthorizedAccessException e) { // This code just writes out the message and continues to recurse. // You may decide to do something different here. For example, you // can try to elevate your privileges and access the file again. Console.WriteLine(e.Message); } catch (System.IO.DirectoryNotFoundException e) { Console.WriteLine(e.Message); } if (files != null) { foreach (System.IO.FileInfo fi in files) { // In this example, we only access the existing FileInfo object. If we // want to open, delete or modify the file, then // a try-catch block is required here to handle the case // where the file has been deleted since the call to TraverseTree(). //Console.WriteLine(fi.Name); File newFile = new File(fi.Name, fi.Length); newFolder.Files.Add(newFile); } // Now find all the subdirectories under this directory. subDirs = root.GetDirectories(); foreach (System.IO.DirectoryInfo dirInfo in subDirs) { folder.Folders.Add(newFolder); // Resursive call for each subdirectory. WalkDirectoryTree(dirInfo, newFolder); } } }