Question

I'm looking for a way to improve my File Search.

Currently i'm working with this Method:

public IEnumerable<FileInfo> FindFilesInDirectory(string dirPath, string searchName)
{
    return Directory.Exists(dirPath)
               ? Directory.GetFiles(dirPath, "*.*", SearchOption.AllDirectories)
                          .ToList()
                          .ConvertAll(x => new FileInfo(x))
                          .Where(x => x.Name.ToLower().Contains(searchName.ToLower()))
               : null;
}

Is there any faster or better way to do this?

Thanks

Was it helpful?

Solution

Nearly micro-optimization, however, you can improve readability and you could add exception handling.

You should also use EnumerateFiles(if possible) which does not need to load all into memory before it starts filtering. Also, use Equals with StringComparison.OrdinalIgnoreCase instead of ToLower since it's more efficient and less error-prone(the Turkey test).

public IEnumerable<FileInfo> FindFilesInDirectory(string dirPath, string searchName)
{
    if (Directory.Exists(dirPath))
    {
        var dir = new DirectoryInfo(dirPath);
        return dir.EnumerateFiles("*.*", SearchOption.AllDirectories)
                  .Where(fi => fi.Name.Equals(searchName, StringComparison.OrdinalIgnoreCase));
    }
    else
        throw new ArgumentException("Directory doesn't exist.", dirPath);
}

OTHER TIPS

There's an overload that will search for a particular pattern. Instead of searching for *.* search for the filename you are interested in with the search pattern parameter.

Directory.GetFiles(dirPath, "*" + searchName + "*", SearchOption.AllDirectories);
return Directory.Exists(dirPath)
           ? Directory.EnumerateFiles(
                dirPath, 
                string.Format("*{0}*",searchName), 
                SearchOption.AllDirectories)
              .Select(x => new FileInfo(x))
           : null;
public IEnumerable<FileInfo> FindFilesInDirectory(string dirPath, string searchName)
{
    return Directory.Exists(dirPath)
               ? Directory.GetFiles(dirPath, "*" + searchName + "*", SearchOption.AllDirectories)
                          .Select(x => new FileInfo(x))
               : null;
}

I don't know what you're doing with your results, but I think it's worth mentioning that the execution of the query in your method will be deferred until you implement it. So depending on what you're doing with the query, it might slow down execution. If this wasn't intended, just add a .toList() to return a list for immediate execution.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top