using System.Collections.Generic; using System.IO; using System.Linq; namespace WpfTreeView { /// /// A helper class to query information about directories /// public static class DirectoryStructure { /// /// Gets all logical drives on the computer /// /// public static List GetLogicalDrives() { // Get every logical drive on the machine return Directory.GetLogicalDrives().Select(drive => new DirectoryItem { FullPath = drive, Type = DirectoryItemType.Drive }).ToList(); } /// /// Gets the directories top-level content /// /// The full path to the directory /// public static List GetDirectoryContents(string fullPath) { // Create empty list var items = new List(); #region Get Folders // Try and get directories from the folder // ignoring any issues doing so try { var dirs = Directory.GetDirectories(fullPath); if (dirs.Length > 0) items.AddRange(dirs.Select(dir => new DirectoryItem { FullPath = dir, Type = DirectoryItemType.Folder })); } catch { } #endregion #region Get Files // Try and get files from the folder // ignoring any issues doing so try { var fs = Directory.GetFiles(fullPath); if (fs.Length > 0) items.AddRange(fs.Select(file => new DirectoryItem { FullPath = file, Type = DirectoryItemType.File })); } catch { } #endregion return items; } #region Helpers /// /// Find the file or folder name from a full path /// /// The full path /// public static string GetFileFolderName(string path) { // If we have no path, return empty if (string.IsNullOrEmpty(path)) return string.Empty; // Make all slashes back slashes var normalizedPath = path.Replace('/', '\\'); // Find the last backslash in the path var lastIndex = normalizedPath.LastIndexOf('\\'); // If we don't find a backslash, return the path itself if (lastIndex <= 0) return path; // Return the name after the last back slash return path.Substring(lastIndex + 1); } #endregion } }