2011-12-15 2 views
7

C#에서 와일드 카드로 상대 경로 인 경로와 상대 경로가있는 경우 및 "..\blah\*.cpp"은 간단한 파일 경로 인 { "c:\foo\blah\a.cpp", "c:\foo\blah\b.cpp" }의 목록을 가져 오는 간단한 방법입니까?C#에서 와일드 카드로 상대 경로 해결

배경 : 소스 파일을 지정하기 위해 와일드 카드로 상대 경로를 사용하는 빌드 정의 파일을 모든 디렉토리에 포함 할 수있는 소스 트리가 있습니다. 여기서 수행 할 작업은 각 빌드 정의 파일에 대한 모든 소스 파일의 절대 경로 목록을 생성하는 것입니다.

+0

System.IO.Directory.EnumerateFiles 당신이 된 searchPattern PARAM에 와일드 카드를 지정할 수 있습니다를 참조하십시오 : http://msdn.microsoft.com/en-us/library/dd413233.aspx 절대 경로를 반환합니다 – Polity

+0

@Polity, System.ArgumentException : 검색 패턴 ".."디렉터리를 위로 이동할 수 없습니다. –

답변

3

가 먼저 절대 경로를 얻을 다음 와일드 카드와 일치하는 디렉토리 내부의 파일을 열거 할 수 있습니다 :

// input 
string rootDir = @"c:\foo\bar"; 
string originalPattern = @"..\blah\*.cpp"; 

// Get directory and file parts of complete relative pattern 
string pattern = Path.GetFileName (originalPattern); 
string relDir = originalPattern.Substring (0, originalPattern.Length - pattern.Length); 
// Get absolute path (root+relative) 
string absPath = Path.GetFullPath (Path.Combine (rootDir ,relDir)); 

// Search files mathing the pattern 
string[] files = Directory.GetFiles (absPath, pattern, SearchOption.TopDirectoryOnly); 
+0

Path.GetFullPath () throw ArgumentException : 패스에 와일드 카드가 포함되어 있으면 경로에 잘못된 문자가 있습니다. –

+0

맞습니다. 상대 검색 패턴을 먼저 디렉토리 및 파일 정보로 나누고 이후에 절대 경로를 결정하도록 코드를 업데이트했습니다 –

+0

작동합니다! 문자열의 relDir = originalPattern.Substring (0, originalPattern.Length - pattern.Length); 우리는 문자열의 relDir = Path.GetDirectoryName (originalPattern);을 사용할 수 있습니다. –

0

간단합니다.

using System.IO; 
     . 
     . 
     . 
string[] files = Directory.GetFiles(@"c:\", "*.txt", SearchOption.TopDirectoryOnly);