If I understand your question correctly (you want to list not only the files in the selected directory, but also the subdirectories), you need to look at the GetDirectories of the DirectoryInfo class.
You could do something like this, perhaps:
DirectoryInfo di = new DirectoryInfo(strSelectedPath); // first list sub-directories DirectoryInfo[] dirs = di.GetDirectories(); foreach (DirectoryInfo dir in dirs) { listView1.Items.Add(dir.Name); } // then list the files FileInfo[] files = di.GetFiles(); foreach (FileInfo file in files) { listView1.Items.Add(file.Name); }
Update: I would suggest that you move the above code into a separate method that takes a string parameter for the path (something like ListDirectoryContents(string path) ). In this method, you can start by clearing items from the list, setting label text, and adding new content as described above.
You can call this method from your btnOpen_Click method by passing folderBrowserDialog1.SelectedPath to the path parameter.
Usually I try to keep my event handlers as small as possible, it is advisable that they do not do any real work, but simply call some other method that does this work. This opens up a bit more to run the same functionality from other places.
Say, for example, that your application can use the path as a command-line parameter, then it will be cleaner code, just calling ListDirectoryContents using the path from the command line, than possibly duplicating the same behavior in your form.
Full code example of this approach:
private void btnOpen_Click(object sender, EventArgs e) { string path = BrowseForFolder(); if (path != string.Empty) { ListDirectoryContent(path); } } private string BrowseForFolder() { FolderBrowserDialog fbd = new FolderBrowserDialog(); if (fbd.ShowDialog() == DialogResult.OK) { return fbd.SelectedPath; } return string.Empty; } private void ListDirectoryContent(string path) { label1.Text = path; listView1.Items.Clear(); DirectoryInfo di = new DirectoryInfo(path);
The surface of this code is that you can reuse the BrowseForFolder method when you need to search for a folder, because it just returns the selected path and is not related to what the path will be used for. Similarly, the ListDirectoryContent method does not completely know where the path comes from; it can come from a folder browser, it can be obtained from the command line or elsewhere.
If you focus on ensuring that your methods perform only their โmain taskโ, relying on input parameters for any additional information that they need, you will get code that is easier to use and maintain.
When it comes to event handlers (like btnOpen_Click), I like to see them as triggers; they make things happen, but they donโt really do much.