C#에서 파일의 크기를 확인하려면 System.IO 네임스페이스에 포함된 FileInfo 클래스를 사용하면 됩니다. FileInfo 클래스는 파일 생성, 삭제, 읽기 등 파일 관련 다양한 작업을 수행할 수 있는 속성과 메서드를 제공하며, 내부적으로 StreamWriter 클래스를 사용해 파일에 데이터를 기록할 수도 있습니다.
FileInfo 클래스의 주요 속성
- Directory – 파일이 위치한 부모 디렉터리를 나타내는 객체를 반환합니다.
- DirectoryName – 파일의 부모 디렉터리 전체 경로를 반환합니다.
- Exists – 파일을 조작하기 전에 해당 파일의 존재 여부를 확인합니다.
- IsReadOnly – 파일이 수정 가능한지 여부를 나타내는 값을 가져오거나 설정합니다.
- Length – 파일의 크기를 바이트 단위로 반환합니다.
- Name – 파일의 이름을 반환합니다.
파일 크기를 구하려면 Length 속성을 사용하며, 이 값은 long 형식으로 바이트 단위로 제공됩니다.
예제 1: 특정 파일의 크기 구하기
class Program{
public static void Main(){
var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp\Data.csv";
long length = new System.IO.FileInfo(path).Length;
System.Console.WriteLine(length);
}
}출력 결과
12
위 예제에서는 Data.csv 파일의 크기가 12바이트임을 확인할 수 있습니다.
예제 2: 디렉터리 내 모든 파일의 크기 구하기
DirectoryInfo 클래스와 함께 GetFiles() 메서드를 사용하면 특정 디렉터리에 있는 모든 파일의 정보를 배열로 가져올 수 있습니다.
class Program{
public static void Main(){
var path = @"C:\Users\Koushik\Desktop\Questions\ConsoleApp";
DirectoryInfo di = new DirectoryInfo(path);
FileInfo[] fiArr = di.GetFiles();
Console.WriteLine("The directory {0} contains the following files:", di.Name);
foreach (FileInfo f in fiArr)
Console.WriteLine("The size of {0} is {1} bytes.", f.Name, f.Length);
}
}출력 결과
The directory ConsoleApp contains the following files:
The size of ConsoleApp.csproj is 333 bytes.
The size of Data.csv is 12 bytes.
The size of Program.cs is 788 bytes.
정리
C#에서 파일 크기를 얻는 가장 간단한 방법은 FileInfo 객체를 생성하고 Length 속성을 읽는 것입니다. 단일 파일뿐만 아니라 DirectoryInfo.GetFiles() 메서드를 활용하면 디렉터리 내 전체 파일의 크기를 한 번에 조회할 수 있어, 파일 관리 프로그램이나 용량 분석 도구를 개발할 때 매우 유용하게 사용됩니다.