为ListView接口指定特定的文件类型

时间:2017-01-22 18:13:34

标签: c# file explorer filechooser

我在C#中创建了一个文件资源管理器,用于从目录列表中选择一个文件,但是我对如何指定文件类型本身知之甚少。

我只想显示.xls个文件,而不是所有显示的文件。我该怎么做?我目前有:

TreeNode newSelected = e.Node;
listView1.Items.Clear();
DirectoryInfo nodeDirInfo = (DirectoryInfo)newSelected.Tag;
ListViewItem.ListViewSubItem[] subItems;
ListViewItem item = null;

foreach (DirectoryInfo dir in nodeDirInfo.GetDirectories())
{
    item = new ListViewItem(dir.Name, 0);
    subItems = new ListViewItem.ListViewSubItem[]
              {new ListViewItem.ListViewSubItem(item, "Directory"),
       new ListViewItem.ListViewSubItem(item,
    dir.LastAccessTime.ToShortDateString())};
    item.SubItems.AddRange(subItems);
    listView1.Items.Add(item);
}
foreach (FileInfo file in nodeDirInfo.GetFiles())
{
    item = new ListViewItem(file.Name, 1);
    subItems = new ListViewItem.ListViewSubItem[]
              { new ListViewItem.ListViewSubItem(item, "File"),
       new ListViewItem.ListViewSubItem(item,
    file.LastAccessTime.ToShortDateString())};

    item.SubItems.AddRange(subItems);
    listView1.Items.Add(item);
}

2 个答案:

答案 0 :(得分:2)

DirectorInfo.GetFiles("*.xls");

会给你那个过滤器。

答案 1 :(得分:1)

您可以将第二个for循环更改为:

foreach (var file in nodeDirInfo.GetFiles())
{
    if (file.Extension == ".xls")
    {
        // Do the stuff with the file
    }
}

foreach (var file in nodeDirInfo.GetFiles()
    .Where(file => 
        string.Equals(file.Extension, ".xls")))
{
    // Do the stuff with the file
}

出于您的目的,我建议您使用OpenFileDialog,因为您只需要用户从目录中选择一个文件:

var openFileDialog1 = new OpenFileDialog();

openFileDialog1.InitialDirectory = @"C:\Path\To\Directory\";
openFileDialog1.Filter = "Excel Files (*.xls)|*.xls";

if (openFileDialog1.ShowDialog() == DialogResult.OK)
{
    var selectedFilePath = openFileDialog1.FileName;
}