Matt McManis
Matt McManis

Reputation: 4675

Force File Browser to Sort files by Name

I have a button that opens a file browser and select multiple files, then adds them to a ListView.

How can I force the Browser Dialog Box to always sort the files by name before being added to the ListView?

Sometimes windows defaults to Date Modified or another sorting method besides Name.


Note: I have full file paths in a List, and just file names in the ListView.

private void btnInput_Click(object sender, RoutedEventArgs e)
{
    // Open Select File Window
    Microsoft.Win32.OpenFileDialog selectFiles = new Microsoft.Win32.OpenFileDialog();

    selectFiles.Multiselect = true;

    // Process Dialog Box
    Nullable<bool> result = selectFiles.ShowDialog();

    if (result == true)
    {
        // Add Path+Filename to List
        foreach (String file in selectFiles.FileNames)
        {
            lstFilesPaths.Add(file);
        }

        // Add List Filename to ListView
        lsvFiles.Items.Clear();
        foreach (String name in fileList)
        {
            lsvFileNames.Items.Add(Path.GetFileName(name));
        }
    }
}

file browser

Upvotes: 0

Views: 1036

Answers (2)

andrensairr
andrensairr

Reputation: 450

The filebrowser itself won't sort its results by filename, you will need to do that before using them.

Given lstFilesPaths is a List of strings you're saving the selected file paths to for use elsewhere, try this to sort the list by file name adding:

foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)).OrderBy(s => s))
{
    lsvFileNames.Items.Add(name);
}

Or, if you'd like both your list of file paths and the list view of file names sorted, try this:

// Add Path+Filename to List
lstFilesPaths.AddRange(selectFiles.FileNames.OrderBy(f => Path.GetFileName(f)));

// Add List Filename to ListView
lsvFiles.Items.Clear();
foreach (var name in lstFilesPaths.Select(f => Path.GetFileName(f)))
{
    lsvFileNames.Items.Add(name);
}

Upvotes: 1

Matt.G
Matt.G

Reputation: 3609

try changing to:

lstFilePaths.AddRange(selectFiles.FileNames.OrderBy(x => x))
lsvFileNames.Items.Clear();
lstFilePaths.ForEach(x => lsvFileNames.Items.Add(Path.GetFileName(x)));

Upvotes: 0

Related Questions