C# 파일 작업 실전 가이드: File 클래스로 존재 확인, 읽기, 복사, 삭제
C# 파일 작업 실전 가이드
C#과 .NET에서 파일 작업은 흔한 요구사항입니다. 파일 존재 확인, 내용 읽기, 파일 복사 관리 등 System.IO.File 클래스는 단순하고 스레드 안전 메서드를 제공합니다. 아래에서 모범 사례와 Microsoft 공식 가이드라인을 따르는 간결한 설명과 샘플 코드를 확인하세요.
기본 파일 작업
- 읽기 – 기존 파일에서 데이터 검색
- 쓰기 – 새 콘텐츠로 파일 전체 덮어쓰기 (기본 동작)
- 추가 – 기존 콘텐츠 삭제 없이 파일 끝에 데이터 추가
다룰 주요 메서드
File.Exists – 파일 존재 여부 확인
File.ReadAllLines – 모든 줄을 문자열 배열로 로드
File.ReadAllText – 전체 파일을 단일 문자열로 로드
File.Copy – 파일을 새 위치로 복제
File.Delete – 파일 시스템에서 파일 제거
전제 조건
모든 예제에서 다음 두 줄이 있는 텍스트 파일 D:\Example.txt가 존재한다고 가정합니다:
Guru99 – .Net
Guru99 – C#
1. 파일 존재 확인 – File.Exists
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
if (File.Exists(path)) {
Console.WriteLine("File Exists");
} else {
Console.WriteLine("File Not Found");
}
Console.ReadKey();
}
}
}
D:\Example.txt가 존재하면 File Exists 출력.
2. 줄별 읽기 – File.ReadAllLines
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
string[] lines = File.ReadAllLines(path);
foreach (var line in lines) {
Console.WriteLine(line);
}
Console.ReadKey();
}
}
}
파일의 각 줄이 별도 콘솔 줄로 출력.
3. 전체 파일 읽기 – File.ReadAllText
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
string content = File.ReadAllText(path);
Console.WriteLine(content);
Console.ReadKey();
}
}
}
콘솔에 두 줄이 줄바꿈과 함께 연결되어 표시.
4. 파일 복사 – File.Copy
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string source = "D:\\Example.txt";
string destination = "D:\\ExampleNew.txt";
File.Copy(source, destination, overwrite: true);
Console.WriteLine("Copy succeeded");
Console.ReadKey();
}
}
}
새 파일 D:\ExampleNew.txt에 Example.txt의 정확한 복사본 생성.
5. 파일 삭제 – File.Delete
using System;
using System.IO;
namespace DemoApplication {
class Tutorial {
static void Main(string[] args) {
string path = "D:\\Example.txt";
File.Delete(path);
Console.WriteLine("File deleted");
Console.ReadKey();
}
}
}
실행 후 D:\Example.txt가 D 드라이브에서 영구 제거.
요약
System.IO.File 클래스는 필수 파일 시스템 연산 제공
File.ReadAllText 또는 File.ReadAllLines로 파일 데이터를 애플리케이션에 로드
- 프로덕션 코드에서는
FileNotFoundException, UnauthorizedAccessException 등 예외 처리 필수