Ahmad Raza
Ahmad Raza

Reputation: 1929

Directory.GetFiles() method in C#

Recently i am working on my class assignment, in which i need to get multiple files from a directory with different extensions. I use this code:

    List<string> Extensions =new List<string>() ;
    Extensions.InsertRange(3, new string[] { "*.txt", "*.htt","*.bat"});
    FolderBrowserDialog _fBrowser = new FolderBrowserDialog();
    if (_fBrowser.ShowDialog() == DialogResult.OK)
    {
        tbPath.Text = _fBrowser.SelectedPath;
        foreach (var item in Extensions)
        {
            SearchFiles(item);    
        }

    } 

In SearchFile() i use this line to search a file on base of extension:

     private void SearchFile(string extension)
     {
         Files = Directory.GetFiles(tbPath.Text, extension).ToList();
     }

If I want to search files with .txt, .htt and .bat extensions from a directory and if there is not any file with .txt extension in current directory then it cause an exception that "Path is not legal" but i want to continue search on base of next extension(.htt). What i can do?

Upvotes: 0

Views: 2061

Answers (2)

Alexander Petrov
Alexander Petrov

Reputation: 14231

You can use something like this:

var extensions = new string[] { ".txt", ".htt", ".bat" };

var foundFiles = Directory.EnumerateFiles(path, "*.*")
    .Where(file => extensions.Contains(Path.GetExtension(file), StringComparer.OrdinalIgnoreCase));

Upvotes: 3

Mostafiz
Mostafiz

Reputation: 7352

Use try catch block

    List<string> Extensions =new List<string>() ;
    Extensions.InsertRange(3, new string[] { "*.txt", "*.htt","*.bat"});
    FolderBrowserDialog _fBrowser = new FolderBrowserDialog();
    if (_fBrowser.ShowDialog() == DialogResult.OK)
    {
        tbPath.Text = _fBrowser.SelectedPath;
        foreach (var item in Extensions)
        {
            try{
                 SearchFiles(item);  
               }
            catch(Exception ex) { };
        }

    }

Upvotes: 2

Related Questions