Wednesday, April 18, 2007

Today someone asked how they might enumerate all files and folders on a device.  The concept is pretty simple, and implementing it with a recursive algorithm is straightforward.  To make it a bit more useful I'm adding the items to a TreeView and saving the full path to the display file/folder in the TreeNode's Tag property, so when a node is selected, you don't have to reassemble the path.

Code:

public void GetListOfAllFilesAndFolders(TreeView view)
{
    view.BeginUpdate();
    view.Nodes.Clear();
    TreeNode node = new TreeNode("My Device");

    AddFolderToTreeNode("\\", node);
    view.Nodes.Add(node);
    view.EndUpdate();
}

private void AddFolderToTreeNode(string rootPath, TreeNode rootNode)
{
    // add in all directories
    string[] dirList = Directory.GetDirectories(rootPath);

    foreach (string dir in dirList)
    {
        TreeNode node = new TreeNode(Path.GetFileName(dir));
        node.Tag = dir;
        AddFolderToTreeNode((string)node.Tag, node);
        rootNode.Nodes.Add(node);
    }

    // add all files
    string[] fileList = System.IO.Directory.GetFiles(rootPath);

    foreach (string file in fileList)
    {
        TreeNode node = new TreeNode(Path.GetFileName(file));
        node.Tag = file;
        rootNode.Nodes.Add(node);
    }
}

Usage:

GetListOfAllFilesAndFolders(treeView1);

Yes, It's that simple.

NOTE: I tested this on an OLDI 56SAM-400 800MHz x86 CE device running CE 5.0 so your mileage may vary.

4/18/2007 12:41:01 PM (Eastern Daylight Time, UTC-04:00)  #    Comments [0]  | 
Name
E-mail
Home page

Comment (HTML not allowed)  

Enter the code shown (prevents robots):