Mike
Mike

Reputation: 249

How to filter files when listing directories in C#

I am trying to filter outout of a method, so only files with a "FF-" prefix will be returned.

My code is as follows:

 DirectoryInfo dinfo = new DirectoryInfo(@"C:\Windows\system32\tasks");
            FileInfo[] Files = dinfo.GetFiles("*.*");
            foreach (FileInfo file in Files)
            {
                listBox1.Items.Add(file.Name);
            }

Upvotes: 1

Views: 239

Answers (3)

Jalal Said
Jalal Said

Reputation: 16162

You can apply search pattern "FF-*" -or "FF-*.txt" for .txt files only-, however if want to get the files paths only then using Directory.GetFiles is better choice

string[] files = Directory.GetFiles(@"C:\Windows\system32\tasks", "FF-*.*");

foreach (string filePath in Files)
{
    listBox1.Items.Add(file.Name);
}

Upvotes: 1

Alex Aza
Alex Aza

Reputation: 78537

Like this?

FileInfo[] Files = dinfo.GetFiles("FF-*.*");

Directory.GetFiles Method

Quote:

* - Zero or more characters.  
? - Exactly zero or one character. 

For example, the searchPattern string "*t" searches for all names in path ending with the letter "t". The searchPattern string "s*" searches for all names in path beginning with the letter "s".

Upvotes: 2

bevacqua
bevacqua

Reputation: 48566

have you tried this?

FileInfo[] Files = dinfo.GetFiles("FF-*.*");

Upvotes: 0

Related Questions