본문 바로가기

개 발코딩

c# 하위 디렉토리 포함하여 파일 검색하기

먼저 소스를 공개하겠다.


namespace FileReader {     class Program     {         static int count = 1;         static void Main(string[] args)         {             DirFileSearch(@"D:\데이터""dat");         }         static void DirFileSearch(string path, string file)         {                          try             {                 string[] dirs = Directory.GetDirectories(path);                 string[] files = Directory.GetFiles(path, $"*.{file}");                 foreach(string f in files)                 {                     // 이 곳에 해당 파일을 찾아서 처리할 코드를 삽입하면 된다.                     Console.WriteLine($"[{count++}] path - {f}");                                     }                                      if(dirs.Length > 0)                 {                     foreach(string dir in dirs)                     {                         DirFileSearch(dir, file);                     }                 }                             }             catch(Exception ex)             {                 Console.WriteLine(ex);                 }           }     } }

순환하면서 하단의 디렉터리의 파일까지 검색하기위해서는 재귀함수를 사용해야 한다.

소스를 간단하게 설명하자면, 재귀함수는 매개변수로 검색 경로와 파일 확장자 타입을 받는다.

먼저 dirs 배열 변수와 files 변수에 현재 위치에서 절대경로를 포함한 디렉토리명과 파일명을 가져온다.

그리고 먼저 files 변수를 foreach 문을 통해 반복하여 읽어들이면서 처리하고, dirs 배열에 길이가 0보다 크다면 디렉토리가 있다는 것이니, 자기 자신을 재귀 호출한다.


매우 간단하다.