반응형
해당 경로 폴더 안에 모든 파일 찾기
원하는 경로를 지정해서 DirectoryInfo 객체를 생성해서 GetFiles() 매서드를 호출하면 해당 파일 내에 존재하는 모든 파일에 대한 정보를 얻을 수 있다. (폴더는 조회되지 않는다.)
DirectoryInfo di = new DirectoryInfo(filePath);
foreach (FileInfo fi in di.GetFiles())
{
Console.WriteLine($"파일 이름 : {fi.Name}");
}
해당 경로 폴더 안에 모든 폴더 찾기
원하는 경로를 지정해서 DirectoryInfo 객체를 생성해서 GetDirectories() 매서드를 호출하면 해당 파일 내에 존재하는 모든 폴더에 대한 정보를 얻을 수 있다. (파일은 조회되지 않는다.)
DirectoryInfo di = new DirectoryInfo(filePath);
foreach (DirectoryInfo d in di.GetDirectories())
{
Console.WriteLine($"폴더 이름 : {d.Name}");
Console.WriteLine($"폴더 확장자 : {d.Extension}");
}
전체 코드
namespace DirectorySearch
{
internal class Program
{
static void Main(string[] args)
{
var filePath = "{원하는 경로 입력}";
DirectoryInfo di = new DirectoryInfo(filePath);
foreach (FileInfo fi in di.GetFiles())
{
Console.WriteLine($"파일 이름 : {fi.Name}");
Console.WriteLine($"파일 전체 경로 : {fi.FullName}");
Console.WriteLine($"파일 확장자 : {fi.Extension}");
}
}
}
}
하위 경로를 포함하여 폴더 안에 있는 모든 파일 이름 가져오기
Directory.GetFiles() 매서드에 대한 설명
- folerPath : 검색할 파일 경로
- *.* : 모든 이름 그리고 모든 확장자 파일을 의미함. (즉 모든 파일)
- SearchOption.AllDirectories : 하위 폴더를 포함하여 검색
using System;
using System.IO;
class Program
{
static void Main(string[] args)
{
string folderPath = @"C:\YourFolderPath"; // 대상 폴더 경로
// 하위 디렉토리를 포함한 모든 파일 가져오기
string[] allFiles = Directory.GetFiles(folderPath, "*.*", SearchOption.AllDirectories);
Console.WriteLine($"Total files found: {allFiles.Length}");
foreach (string file in allFiles)
{
Console.WriteLine(file); // 파일 경로 출력
}
}
}
폴더 구조 예시
C:\YourFolderPath
│
├── File1.txt
├── SubFolder1
│ ├── File2.txt
│ ├── File3.docx
├── SubFolder2
│ ├── File4.png
│ ├── File5.jpg
출력 결과
폴더를 제외한 하위 모든 파일에 대한 정보가 출력된다.
Total files found: 5
C:\YourFolderPath\File1.txt
C:\YourFolderPath\SubFolder1\File2.txt
C:\YourFolderPath\SubFolder1\File3.docx
C:\YourFolderPath\SubFolder2\File4.png
C:\YourFolderPath\SubFolder2\File5.jpg
'프로그래밍 > C#' 카테고리의 다른 글
C# StackExchange 사용해서 redis에 객체 저장하고 불러오기 (0) | 2025.01.13 |
---|---|
C# 웹앱에서 appsettings.json 설정값 사용하기 (0) | 2025.01.07 |
C# 업그레이드된 자동 구현 속성(Auto-Implement Property)에 대해서 (0) | 2024.12.29 |
C# Count vs Count() 차이에 대해서 (0) | 2024.12.16 |
C# 속성(Property)이란 무엇인가 (1) | 2024.12.12 |
댓글