I have some functions that allow a user to search through multiple directories for files of a certain type, and then just the path of those files is added to a listbox
. Right now it's done through some nested foreach
statements. It's going to be retrieving hundreds of thousands of filepaths, so I was curious what other efficient ways there would be to go about this?
Also, I know it sounds dumb to add that many items to a listbox
. I'm only doing what I was told to do. I have a feeling in the future it will be asked to get rid of, but the filepaths will still have to be stored in a list somewhere.
Note: I'm using the WindowsAPICodePack
to get a dialogue box that allows multiple directory selection.
List<string> selectedDirectories = new List<string>();
/// <summary>
/// Adds the paths of the directories chosen by the user into a list
/// </summary>
public void AddFilesToList()
{
selectedDirectories.Clear(); //make sure list is empty
var dlg = new CommonOpenFileDialog();
dlg.IsFolderPicker = true;
dlg.AddToMostRecentlyUsedList = false;
dlg.AllowNonFileSystemItems = false;
dlg.EnsureFileExists = true;
dlg.EnsurePathExists = true;
dlg.EnsureReadOnly = false;
dlg.EnsureValidNames = true;
dlg.Multiselect = true;
dlg.ShowPlacesList = true;
if (dlg.ShowDialog() == CommonFileDialogResult.Ok)
{
selectedDirectories = dlg.FileNames.ToList(); //add paths of selected directories to list
}
}
/// <summary>
/// Populates a listbox with all the filepaths of the selected type of file the user has chosen
/// </summary>
public void PopulateListBox()
{
foreach (string directoryPath in selectedDirectories) //for each directory in list
{
foreach (string ext in (dynamic)ImageCB.SelectedValue) //for each file type selected in dropdown
{
foreach (string imagePath in Directory.GetFiles(directoryPath, ext, SearchOption.AllDirectories)) //for each file in specified directory w/ specified format(s)
{
ListBox1.Items.Add(imagePath); //add file path to listbox
}
}
}
}
Edit: Not sure if it makes a difference, but I'm using the WPF
listbox
, not winforms
.