-4

Is there any way to view filesystem directly on the form with similar functionality as OpenFileDialog (opening folders, selecting files) in Visual Studio C#?

AndrewR
  • 592
  • 2
  • 6
  • 20
  • 3
    Yes, of course there is. If you are asking if there is a built-in control you can drop on the form, then no. Otherwise the way is to use the `System.IO` `File` and `Directory` classes to recurse through the entries on the drive, and I would suggest lazy loading. – Ron Beyer Aug 31 '15 at 15:19
  • Nothing annoys me more than applications that try to implement their own file browsers that go around the shell. – James R. Aug 31 '15 at 16:55

1 Answers1

1

Try this:

private void Button1_Click(object sender, EventArgs e)
{
     ListDirectory("Your TreeView Name here", "root path")
}

private void ListDirectory(TreeView tv, string path)
{
    tv.Nodes.Clear();
    var rootDirectoryInfo = new DirectoryInfo(path);
    tv.Nodes.Add(CreateDirectoryNode(rootDirectoryInfo));
}

private static TreeNode CreateDirectoryNode(DirectoryInfo directoryInfo)
{
    var directoryNode = new TreeNode(directoryInfo.Name);
    foreach (var directory in directoryInfo.GetDirectories())
        directoryNode.Nodes.Add(CreateDirectoryNode(directory));
    foreach (var file in directoryInfo.GetFiles())
        directoryNode.Nodes.Add(new TreeNode(file.Name));
    return directoryNode;
}
thewisegod
  • 1,524
  • 1
  • 10
  • 11
  • This is a cross-threading violation, and in principle its right, but using something like the root path will cause the application to stop responding while it recursively loads the entire drive. You may also get stack overflow exceptions if the folder path is sufficiently deep. – Ron Beyer Aug 31 '15 at 15:35