Martin Sebastian Martin Sebastian - 22 days ago 5
C# Question

How to find all exe's in hard disk?

How can I find all executables on hard disk satisfying following conditions
1. Skip to next folder if a folderis not accessible while searching
2. Skip to next folder if a path is too long while searching

Here is my code:

public static string[] GetFiles(string path, string searchPattern, SearchOption searchOption)
{
///meth1
while (true)
{
string[] searchPatterns = searchPattern.Split('|');
List<string> files = new List<string>();
try
{
foreach (string sp in searchPatterns)
files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
}
catch (UnauthorizedAccessException UAEx)
{
MessageBox.Show(UAEx.Message);
continue;
}
catch (PathTooLongException ex)
{
MessageBox.Show(ex.Message);
continue;
}
files.Sort();
return files.ToArray();
}
}

Answer

You said :

how to skip to next folder.. for eg : if C://users/demo/abc is a folder and demo doesn'y have access permisison, the current code goes to next folder on Demo.. how to skip to next folder in User

Your code doesn't test the rights on the folder, but catches the rights exceptions caused by the forbidden file access. So, you won't be able to go to the next folder with this solution. You need to refactor the entire code.

In addition, your code seems to have an infinite loop when you don't have the rights on a file. So first, I think you should remove the while loop and put your trycatch expression Inside your foreach loop. That way, your solution will skip the forbidden files. (More ! Your code will only do one time SearchPattern.Split)

foreach (string sp in searchPatterns)
    {
        try
        {
            files.AddRange(System.IO.Directory.GetFiles(path, sp, searchOption));
        }
        catch (UnauthorizedAccessException UAEx)
        {
            MessageBox.Show(UAEx.Message);
            continue;
        }
        catch (PathTooLongException ex)
        {
            MessageBox.Show(ex.Message);
            continue;
        }
    }