728x90
C#의 영역에서 파일 작업은 필수적입니다. System.IO.File 클래스는 .NET 프레임워크의 필수 구성 요소로서 파일 생성, 읽기, 업데이트 및 삭제에 도움이 되는 다양한 정적 메서드를 제공합니다. 이 블로그 게시물에서는 File 클래스의 핵심 메서드를 분석하고 그 유용성을 보여드리겠습니다.
File 클래스 소개
File 클래스는 FileStream 또는 StreamReader/StreamWriter를 수동으로 만들 필요 없이 파일을 관리하는 정적 메서드를 제공합니다. 이 메서드는 다양한 시나리오에서 파일을 처리하는 데 간단하고 효율적으로 설계되었습니다.
자주 사용되는 메서드
- File.Create(string path) : 지정한 경로에 파일을 만들거나 덮어씁니다.
FileStream myFile = File.Create(@"C:\MyDirectory\Sample.txt");
myFile.Close();
- File.Exists(string path) : 지정된 경로에 파일이 있는지 확인합니다.
if (File.Exists(@"C:\MyDirectory\Sample.txt"))
{
Console.WriteLine("File exists.");
}
- File.Delete(string path) : 지정한 파일을 삭제합니다.
File.Delete(@"C:\MyDirectory\ObsoleteFile.txt");
- File.Copy(string sourceFileName, string destFileName, bool overwrite) : 기존 파일을 덮어쓸 수 있는 옵션을 사용하여 파일을 새 위치에 복사합니다.
File.Copy(@"C:\MyDirectory\Source.txt", @"C:\Destination\Copy.txt", true);
- File.Move(string sourceFileName, string destFileName) : 파일을 새 위치로 이동하여 프로세스에서 파일 이름을 효과적으로 변경합니다.
File.Move(@"C:\OldDirectory\OldFile.txt", @"C:\NewDirectory\NewFile.txt");
- File.ReadAllText(string path), File.WriteAllText(string path, string contents) : 파일의 전체 내용을 문자열로 읽고 문자열을 파일에 씁니다.
string content = File.ReadAllText(@"C:\MyDirectory\ReadMe.txt");
File.WriteAllText(@"C:\MyDirectory\WriteMe.txt", "Hello, World!");
- File.ReadAllLines(string path), File.WriteAllLines(string path, string[] contents) : 파일의 모든 줄을 문자열 배열로 읽고 문자열 배열을 파일에 각각 줄로 씁니다.
string[] lines = File.ReadAllLines(@"C:\MyDirectory\Data.txt");
File.WriteAllLines(@"C:\MyDirectory\Output.txt", new string[] { "Line1", "Line2" });
- File.Open(string path, FileMode mode) : 읽기, 쓰기 또는 둘 다와 같은 작업을 허용하는 지정된 모드로 파일을 엽니다.
FileStream fs = File.Open(@"C:\MyDirectory\Sample.txt", FileMode.OpenOrCreate);
// Perform operations on the FileStream 'fs'
fs.Close();
결론
C#의 File 클래스는 파일 작업을 쉽고 정확하게 처리할 수 있는 강력한 도구입니다. 내장된 메서드는 광범위한 공통 파일 작업에 적합하여 개발자가 최소한의 오버헤드로 파일 작업을 수행할 수 있도록 합니다. 항상 그렇듯이, 데이터 무결성과 시스템 안정성을 보장하기 위해 파일 작업 시 예외를 처리하고 모범 사례를 유지하는 것이 필수적입니다.
728x90
'C#' 카테고리의 다른 글
C# 8의 System.Index 및 System.Range (0) | 2023.09.12 |
---|---|
자료구조 : 선형구조와 비선형구조 (0) | 2023.09.04 |
C# : Path (0) | 2023.09.01 |
C# String : IsNullOrEmpty() (0) | 2023.07.16 |
C# : Array 배열 (0) | 2023.07.08 |