2017-09-10 7 views
1

true/false를 반환하는 코드가 있습니다.주어진 디렉토리에 ".exe"가 포함되어 있으면 True 또는 False를 반환하려고합니다.

public static bool HasExecutable(string path) 
    { 
     var exts = "*.exe"; 
     if (path.AsDirectory().Exists) return true; 
     if(path.AsDirectory().GetFiles(exts).Any(i => path.Contains(exts))) return true; 
     return false; 
    } 
} 

} 넣어

내 밖으로 내 프로그램을 중지 오류가, 내가 여기에 몇 가지 논리를 실종인가?

+2

오류 메시지 란 무엇입니까? –

+0

처리되지 않은 예외 : System.IO.DirectoryNotFoundException : 'c : \ program files (x86) \ notepad ++'경로의 일부를 찾을 수 없습니다. . –

+0

@ Aominè i 요소를 사용할 때 오류가 발생했습니다. fileInfo에서 변환 할 수 없습니다. 문자열을 –

답변

1

if (path.AsDirectory().Exists) return true; 

반환 true 디렉토리 자체가 존재하는 경우이 줄.

if (!path.AsDirectory().Exists) return false; 

LINQ 부분도 문제가 : 경로가 와일드 카드 문자를 가질 수 없기 때문에 경로에 Contains 호출 "*.exe" 문자열 true을 반환하지 않습니다 디렉토리가 존재하지 않는 경우 대신 false를 반환해야 .

return path.AsDirectory().GetFiles(exts).Any(); 

당신은 하나의 문에 두 조건을 접을 수 있습니다 :

return path.AsDirectory().Exists 
    && path.AsDirectory().GetFiles(exts).Any(); 
+0

안녕하세요 @ dasblinkenlight 코드를 주셔서 감사하지만 내 테스트 케이스와 함께 변경 사항을 따르십시오 @ "c : \ program files (x86) \ notepad ++"/// true true가 true 메소드를 호출하는 대신 false 값을 반환합니다. false –

+0

@ d.Freeze 이상한 점은 본질적으로 시스템 메서드에 대한 한 줄짜리 호출 인 구현에 특별한 것은 없다는 것입니다. 테스트 케이스를 점검하여 예상 결과가 올바른지 확인하십시오 (exe 파일은이 코드가 작동하려면 서브 디렉토리 중 하나가 아닌 디렉토리 자체에 있어야합니다). – dasblinkenlight

+0

여기 테스트 케이스 // if (true.ToString()! = Practice.HasExecutable (@ "c : \ program files (x86) \ notepad ++") ToString()) { TestFailures.Add (Tuple.Create (@ "c : \ program files (x86) \ notepad ++") ToString(), true.ToString(), Practice.HasExecutable } /// 반환 경로를 추가했습니다 .AsDirectory(). GetFiles (exts, SearchOption.AllDirectories) .Any(); 모든 디렉토리를 검색 할 때 여전히 잘못된 값을 반환합니다 –

3

당신은 단지를 열거 할 수 GetFiles 당신을 위해 필터링을 수행했기 때문에하지만, 전혀 조건이 필요하지 않습니다 디렉토리에 패턴 일치가 있고 Any 확장 메소드를 사용하십시오.

public static bool HasExecutable(string path) 
    { 
     var exts = "*.exe"; 
     return Directory.EnumerateFiles(path, exts).Any(); 
    }