C#에서 파일 경로 처리하기
C#에서 파일 경로를 손쉽게 다루려면 Path 클래스가 제공하는 메서드를 활용하는 것이 가장 효과적입니다. 이 메서드들은 모두 System.IO 네임스페이스에 포함되어 있어, 복잡한 문자열 조작 없이도 파일 이름, 확장자 등 필요한 정보를 간편하게 추출할 수 있습니다.
대표적인 Path 메서드는 다음과 같습니다.
GetExtension() – 파일 확장자 가져오기
GetExtension() 메서드는 파일 경로에서 확장자만 추출하여 반환합니다.
예: .txt, .dat 등
GetFileName() – 파일 이름 가져오기
GetFileName() 메서드는 경로 전체에서 확장자를 포함한 파일 이름을 추출합니다.
예: new.txt, details.dat 등
GetFileNameWithoutExtension() – 확장자 제외한 파일 이름 가져오기
GetFileNameWithoutExtension() 메서드는 확장자를 제외한 파일 이름만 반환합니다.
예: new, details 등
예제 코드
세 가지 메서드를 실제로 활용하는 예제를 살펴보겠습니다.
using System.IO;
using System;
class Program {
static void Main() {
string myPath = "D:\\one.txt";
string fileExtension = Path.GetExtension(myPath);
string fileName = Path.GetFileName(myPath);
string noExtension = Path.GetFileNameWithoutExtension(myPath);
Console.WriteLine("File Extension: " + fileExtension);
Console.WriteLine("File Name: " + fileName);
Console.WriteLine("File Name without extension: " + noExtension);
}
}
실행 결과
File Extension: .txt
File Name: one.txt
File Name without extension: one
정리
위 실행 결과에서 확인할 수 있듯이, GetExtension()은 점(.)을 포함한 확장자를, GetFileName()은 확장자가 붙은 전체 파일 이름을, 그리고 GetFileNameWithoutExtension()은 순수한 파일 이름만 반환합니다. 세 메서드를 적절히 조합하면 업로드 파일 검증, 로그 파일 생성, 확장자별 분류 작업 등 다양한 파일 처리 로직을 깔끔하게 구현할 수 있습니다.