是否可以在末尾添加选定的文件,而不是使用带有多选的OpenFileDialog?

时间:2016-03-11 18:28:30

标签: c# .net openfiledialog

当使用启用了多选的OpenFileDialog时,每次选择其他文件(使用ctrl或shift + click)时,最近添加的文件都会插入文件名文本框的开头。有没有办法改变这一点,并让他们添加到最后?

我正在使用IFileDialog界面进行一些工作来自定义它,文件排序对我来说至关重要。

我正在使用.NET 4.5。

编辑:在做了一些实验之后,我不确定文件在返回后的顺序。它似乎是按字母顺序排列的。任何人都可以验证吗?我无法为此找到好的文档/示例。

1 个答案:

答案 0 :(得分:3)

如果要按照单击它们的确切顺序获取所选文件,则无法使用标准OpenFileDialog,因为无法控制返回的FileNames属性的顺序。 相反,您可以轻松地在特定文件夹中构建自己的ListView文件,并自行跟踪所点击的项目的顺序,从List<string>

添加和删除它们
 List<string> filesSelected = new List<string>();

假设有一个具有这些属性的ListView

// Set the view to show details.
listView1.View = View.Details;

// Display check boxes.
listView1.CheckBoxes = true;
listView1.FullRowSelect = true;
listView1.MultiSelect = false;

// Set the handler for tracking the check on files and their order
listView1.ItemCheck += onCheck;

// Now extract the files, (path fixed here, but you could add a 
// FolderBrowserDialog to allow changing folders....
DirectoryInfo di = new DirectoryInfo(@"d:\temp");
FileInfo[] entries = di.GetFiles("*.*");

// Fill the listview with files and some of their properties
ListViewItem item = null;
foreach (FileInfo entry in entries)
{
    item = new ListViewItem(new string[] { entry.Name, entry.LastWriteTime.ToString(), entry.Length.ToString()} );
    listView1.Items.Add(item);
}            
listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.ColumnContent);                        

// Create columns for the items and subitems.
// Width of -2 indicates auto-size.
listView1.Columns.Add("File name", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Last Write Time2", -2, HorizontalAlignment.Left);
listView1.Columns.Add("Size", -2, HorizontalAlignment.Left);

此时,onCheck事件处理程序可用于从跟踪文件列表中添加和删除文件

void onCheck(object sender, ItemCheckEventArgs e)
{
    if (e.Index != -1)
    {
        string file = listView1.Items[e.Index].Text;
        if (filesSelected.Contains(file))
            filesSelected.Remove(file);
        else
            filesSelected.Add(file);
    }
}