简体   繁体   中英

Display only certain file types from a directory in a listview

I want my listview to only display .PDF files

here is my current code to populate the listview

but I have no idea how to filter the filetypes to only a certain file extension

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

of course you can specify the file type in GetFiles as like this:

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
}

See Can you call Directory.GetFiles() with multiple filters?

Get the files filtered before you attempt to list them?

You can use the GetFiles() override that allows for a searchPattern to be send in. See the document below on how to use the overloaded parameter.

DirectoryInfo.GetFiles()

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM