If you return an array of string (Directory.GetFiles
) then you should loop over the returned list of filenames and add every single item one by one. If you try to add the whole array you will get an exception because the ListViewItemCollection.Add
method cannot handle an array.
However, remember that Directory.GetFiles
with only two parameters returns only the files that match your extension variable and are located EXACTLY in the folder expressed by the path variable (the root of the drive in your case). If any of your MDF files is located in a subfolder of that path variable it is not catched by the above GetFiles call. There is an overload of the GetFiles that takes an enum value instructing the GetFiles method to work recursively on all the underlying subfolders. Its use or not depends on your requirements
private void btnScan(object sender, EventArgs e)
{
string path = cmbDrive.Text;
string extension = "*.mdf";
string[] files = Directory.GetFiles(path, extension);
//string[] files = Directory.GetFiles(path, extension, SearchOption.AllDirectories);
foreach(string s on files)
lstvwdb2.Items.Add(s);
}
Beware that searching on the C: drive with the option AllDirectories could be problematic due to the presence of numerous reserved folders that cause an Exception if you try to read them.
To bypass this problem you could copy the code provided by Marc Gravell in its answer here and paste it in a utility class (for example a FileUts class), then loop using a foreach calling that method instead of Directory.GetFiles
private void btnScan(object sender, EventArgs e)
{
string path = cmbDrive.Text;
string extension = "*.mdf";
foreach(string s in FileUts.GetFiles(path, extension))
lstvwdb2.Items.Add(s);
}
public static class FileUts
{
// Code provided by Marc Gravell
public static IEnumerable<string> GetFiles(string root, string searchPattern)
{
.....
}
}