To demonstrate some of the classes available in the System.IO namespace, a Directory application was built in the Directory directory. By recursing through the directory structure, you can make use of the Directory, File, FileInfo, and DirectoryInfo classes. (This sample application is available in the Directory directory.) Listing B.55 shows a code snippet that initializes a tree control with drive and directory information.
private void InitializeTreeControl() { // Initialize TreeControl. // Populate the TreeView with data. // First add the root node. rootNode = new TreeNode("My Computer", (int)ImageListTypes.Computer, (int)ImageListTypes .Computer); directoryTree.Nodes.Add(rootNode); TreeNodeCollection driveCollection = rootNode.Nodes; // Get a list of logical drives. string [] driveNames = Directory.GetLogicalDrives(); foreach (string s in driveNames) { ImageListTypes imageIndex = ImageListTypes.Computer; ImageListTypes selectedIndex = ImageListTypes.Computer; DriveType dt = (DriveType)NativeMethods.GetDriveTypeW(s); if (dt == DriveType.Removable) { ... } else { ... // For each logical drive find the // directories and files PopulateTreeNode(s, driveNode.Nodes); } ... } |
Notice that it was necessary to drop down to P/Invoke to get the drive type. There doesn't seem to be a class or method to retrieve this information.
Next, the tree is populated on the level beneath. First, you get the names of the files using Directory.GetFiles(path), and then you get the names of the directories using Directory.GetDirectories(path). Listing B.56 shows how this is done.
3.147.104.120