2013-07-02 2 views
2

내 파일 검색을 개선 할 방법을 찾고 있습니다. 디렉토리의 모든 파일을 찾는 더 나은 방법

현재 나는이 방법으로 일하고 있어요 :

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

이 일을 더 빨리 또는 더 나은 방법이 있나요?

감사

+0

FYI : 파일 이름에만 관심이있는 경우 'FileInfo' 개체를 반환하는 것이 더 많은 오버 헤드입니다. –

답변

3

거의 마이크로 최적화, 그러나, 당신은 가독성을 향상시킬 수 있습니다 그리고 당신은 예외 처리를 추가 할 수 있습니다.

필터링을 시작하기 전에 메모리에 모두로드 할 필요가없는 EnumerateFiles (가능한 경우)을 사용해야합니다. 더 효율적이고 오류가 발생하기 쉬운 (the Turkey test)이기 때문에 ToLower 대신 EqualsStringComparison.OrdinalIgnoreCase을 사용하십시오.

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

좋아, 그게 내가 원하는거야. 큰 감사를 드린다! – Smartis

+0

내 기쁨! 이 함수는 실제로 IEnumerable 을 반환합니다. 따라서 반환 값을 변수에 할당하면'Enumerable.Count'와 같은 지연 실행을 사용하지 않는 메서드로이 쿼리를 항상 실행합니다. 이 쿼리를 구체화하려면 ToList()를 추가하면됩니다. 예 :'List files = FindFilesInDirectory (@ "D : \", "data.txt"). ToList();'. 그러나 foreach를 사용하면 새로운 콜렉션을 만들지 않고도이를 열거 할 수있다. –

3

는 특정 패턴을 검색 것 overload있다. 검색 패턴 매개 변수에 관심이있는 파일 이름을 *.*으로 검색하는 대신 검색하십시오.

Directory.GetFiles(dirPath, "*" + searchName + "*", SearchOption.AllDirectories); 
+2

' "*"+ searchName'은'x.Name.ToLower(). Contains (searchName.ToLower())'와 완전히 같지 않으며 includes 검색 대신 endsWith 검색을 나타냅니다. – spender

+0

사실, 동의 및 변경됨. –

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

나는 당신이 당신의 결과로 무슨 일을하는지 모르겠지만, 나는 그것이 당신이 그것을 구현할 때까지 방법에서 쿼리의 실행이 지연됩니다 언급 할 가치가 있다고 생각. 따라서 쿼리를 통해 수행중인 작업에 따라 실행 속도가 느려질 수 있습니다. 이것이 의도하지 않았다면 .toList()를 추가하여 즉시 실행을위한 목록을 반환하십시오.

관련 문제