仅显示列表视图中目录的某些文件类型

时间:2017-01-12 17:25:56

标签: c# listview pdf treeview

我希望我的listview只显示.PDF文件

这是我当前填写listview的代码

但我不知道如何将文件类型过滤到某个文件扩展名

    void treeView1_NodeMouseClick(object sender,
TreeNodeMouseClickEventArgs e)
    {
        uplevel = "";
        TreeNode newSelected = e.Node;
        //sub =


        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);
        }

        listView1.AutoResizeColumns(ColumnHeaderAutoResizeStyle.HeaderSize);
    }

3 个答案:

答案 0 :(得分:1)

当然您可以在GetFiles中指定文件类型,如下所示:

string searchPattern = "*.pdf";
// This pattern will filter files having any name and extension as .pdf
foreach (FileInfo file in nodeDirInfo.GetFiles(searchPattern)
{

    // add items as per your code
}

答案 1 :(得分:0)

请参阅Can you call Directory.GetFiles() with multiple filters?

在尝试列出文件之前获取文件?

答案 2 :(得分:0)

您可以使用允许发送searchPattern的GetFiles()覆盖。请参阅下面的文档,了解如何使用重载参数。

DirectoryInfo.GetFiles()