I’m very new to C#. My boss asked me to wrote some code using listview as a file browser. I tried it and it seems it works. This code is to open the files from your drives and display it on the listView. It’s very simple. I also made an additional function where one can clear the displayed items in the listView. I would like to add additional feature, where I can also open the directory and not only the files.
By the way, here is the sample of my code:
private void btnOpen_Click(object sender, EventArgs e)
{
string strSelectedPath;
folderBrowserDialog1.ShowDialog();
strSelectedPath = folderBrowserDialog1.SelectedPath;
label1.Text = strSelectedPath;
DirectoryInfo di = new DirectoryInfo(strSelectedPath);
FileInfo[] files = di.GetFiles();
foreach (FileInfo file in files)
{
listView1.Items.Add(file.Name);
}
}
private void btnClear_Click(object sender, EventArgs e)
{
listView1.Items.Clear();
label1.Text="";
}
Could you please show me how?
If I understand your question correctly (you want to list not only the files in the selected directory, but also the sub-directories), you will want to look into the GetDirectories method of the DirectoryInfo class.
You could do something like this, perhaps:
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 with clearing the items from the list view, setting the label text and then adding new content as above.This method can be called from your
btnOpen_Clickmethod, passingfolderBrowserDialog1.SelectedPathin the path parameter.I usually try to keep my event handlers as small as possible, preferably not performing any real work but rather just call some other method that does the work. This opens up a bit more for triggering the same functionality from other places.
Say for instance that your application can take a path as a command line parameter, then it will be cleaner code just calling
ListDirectoryContentswith the path from the command line than perhaps duplicating the same behaviour in your form.Full code example of that approach:
The upsides of this code is that you can reuse the method BrowseForFolder whenever you need to browse for a folder, since it simply returns the selected path and is not connected to what the path will be used for. Similarly, the ListDirectoryContent method is completely unaware of from where the path parameter comes; it may come from the folder browser, it may come from the command line or anywhere else.
If you focus on having your methods performing only their “core task”, relying on input parameters for any additional information that they need you will get code that is easier to reuse and maintain.
When it comes to event handlers (such as btnOpen_Click), I like to see them as triggers; they trigger things to happen, but the don’t really do a lot themselves.