C#에서 파일 경로를 처리하고, 파일명, 확장자 등을 가져오는 방법을 보여주는 예시 코드를 공유합니다. 참고해 주세요~
using System;
class Program
{
private static void BEOMSANG()
{
string filePath = string.Empty;
string result = string.Empty;
filePath = @"C:\beomsang\hello.txt";
// 전체 파일명과 확장자
// 결과 : "hello.txt"
result = System.IO.Path.GetFileName(filePath);
Console.WriteLine("전체 파일명: " + result);
// 확장자
// 결과 : ".txt"
result = System.IO.Path.GetExtension(filePath);
Console.WriteLine("확장자: " + result);
// 확장자를 제외한 파일명
// 결과 : "hello"
result = System.IO.Path.GetFileNameWithoutExtension(filePath);
Console.WriteLine("파일명: " + result);
// 파일 경로
// 결과 : "C:\beomsang"
result = System.IO.Path.GetDirectoryName(filePath);
Console.WriteLine("파일 경로: " + result);
}
static void Main(string[] args)
{
BEOMSANG();
}
}
파일의 전체 이름, 확장자, 파일명, 그리고 파일 경로를 각각 조회하는 메서드입니다. 파일 경로를 지정하여 테스트 하면 각 메서드가 정확하게 동작하는지 확인할 수 있을 거예요!
C#에서 파일 경로를 처리하고, 파일명, 확장자 등을 추출하는 방법을 간단한 코드로 안내해드렸는데요, 해당 코드에서 사용한 메서드들의 간단한 설명입니다.
Path.GetFileName()전체 파일 경로에서 '파일명과 확장자'를 추출합니다.예:"C:\beomsang\hello.txt"에서 결과는"hello.txt"입니다.Path.GetExtension()파일의 확장자만 추출합니다.예:"C:\beomsang\hello.txt"에서 결과는".txt"입니다.Path.GetFileNameWithoutExtension()파일명만 추출하고 확장자는 제외합니다.예:"C:\beomsang\hello.txt"에서 결과는"hello"입니다.Path.GetDirectoryName()파일의 디렉터리 경로만 추출합니다.예:"C:\beomsang\hello.txt"에서 결과는"C:\beomsang"입니다.
이 메서드들을 통해 파일 경로에서 필요한 정보를 손쉽게 분리하고 관리할 수 있어, 파일 처리에 매우 유용합니다. System.IO 네임스페이스에 있는 여러 기능을 사용하면 파일과 디렉토리 관련 작업을 좀 더 간편하게 수행할 수 있어요.
