프로그래밍/C#

C#에서 파일과 스트림 처리하기 📁✨

다다면체 2024. 12. 18. 09:36
728x90
반응형
반응형

파일과 스트림은 C#에서 데이터를 저장하거나 읽어오는 데 핵심적인 역할을 합니다. 현업 개발자라면 효율적인 파일 처리가 얼마나 중요한지 공감하실 텐데요! 이번 포스팅에서는 실무에서도 유용하게 활용할 수 있는 파일 입출력 기법과 스트림 활용법을 살펴보겠습니다! 🚀


1. 파일 입출력 (파일 읽기/쓰기) 📝

C#에서는 파일의 읽기와 쓰기를 위해 System.IO 네임스페이스를 제공합니다. 파일 입출력은 크게 텍스트 파일 처리바이너리 파일 처리로 나뉩니다.

텍스트 파일 쓰기 ✍️

using System.IO;

string filePath = "example.txt";
string content = "Hello, World!";

// 파일에 텍스트 쓰기
File.WriteAllText(filePath, content);

Console.WriteLine("파일이 작성되었습니다.");

텍스트 파일 읽기 📖

// 파일에서 텍스트 읽기
string readContent = File.ReadAllText(filePath);
Console.WriteLine($"파일 내용: {readContent}");

바이너리 파일 처리 💾

바이너리 데이터는 FileStream 클래스를 사용하여 처리합니다.

using System.IO;

byte[] data = { 1, 2, 3, 4, 5 };
string binaryFilePath = "binary.dat";

// 파일에 바이너리 데이터 쓰기
using (FileStream fs = new FileStream(binaryFilePath, FileMode.Create))
{
    fs.Write(data, 0, data.Length);
}

Console.WriteLine("바이너리 파일이 작성되었습니다.");

// 파일에서 바이너리 데이터 읽기
using (FileStream fs = new FileStream(binaryFilePath, FileMode.Open))
{
    byte[] readData = new byte[fs.Length];
    fs.Read(readData, 0, readData.Length);
    Console.WriteLine("읽은 데이터: " + string.Join(", ", readData));
}

2. Stream과 StreamReader/StreamWriter의 차이점 🔄

C#에서 스트림은 데이터를 연속적으로 읽거나 쓰는 방식으로 작동합니다. 이를 통해 대용량 데이터를 효율적으로 처리할 수 있습니다.

Stream

Stream은 추상 클래스이며, 파일, 메모리, 네트워크 스트림 등 다양한 데이터 소스를 처리할 수 있는 기본 인터페이스를 제공합니다.

StreamReader / StreamWriter ✨

  • StreamReader: 텍스트 데이터를 읽는 데 최적화된 클래스입니다.
  • StreamWriter: 텍스트 데이터를 쓰는 데 최적화된 클래스입니다.

StreamWriter 예제 🖋️

using System.IO;

string path = "example.txt";

// StreamWriter를 사용하여 텍스트 파일에 쓰기
using (StreamWriter writer = new StreamWriter(path))
{
    writer.WriteLine("안녕하세요!");
    writer.WriteLine("C#의 StreamWriter를 배우는 중입니다.");
}

Console.WriteLine("파일 쓰기가 완료되었습니다.");

StreamReader 예제 📚

// StreamReader를 사용하여 텍스트 파일 읽기
using (StreamReader reader = new StreamReader(path))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

3. 파일 경로 관리와 예외 처리 🔍

파일 작업 시 경로와 예외 처리도 중요한 요소입니다. 잘못된 경로나 접근 권한 문제가 발생할 수 있으므로 이를 대비해야 합니다.

파일 경로 관리 🗺️

  • 상대 경로: 현재 실행 파일 위치를 기준으로 경로를 지정.
  • 절대 경로: 파일 시스템의 루트부터 전체 경로를 지정.
string relativePath = "data\example.txt";
string absolutePath = Path.Combine(Directory.GetCurrentDirectory(), relativePath);

Console.WriteLine($"절대 경로: {absolutePath}");

예외 처리 🛡️

try
{
    string content = File.ReadAllText("nonexistent.txt");
    Console.WriteLine(content);
}
catch (FileNotFoundException ex)
{
    Console.WriteLine("파일을 찾을 수 없습니다: " + ex.Message);
}
catch (UnauthorizedAccessException ex)
{
    Console.WriteLine("파일 접근 권한이 없습니다: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("예기치 못한 오류가 발생했습니다: " + ex.Message);
}

4. 파일을 다루는 다양한 예제 📂

C#에서는 다양한 형식의 파일 (CSV, JSON, XML)을 처리할 수 있습니다.

CSV 파일 처리 🧾

using System.IO;

string csvPath = "data.csv";

// CSV 파일 쓰기
using (StreamWriter writer = new StreamWriter(csvPath))
{
    writer.WriteLine("Name,Age,Email");
    writer.WriteLine("Alice,30,alice@example.com");
    writer.WriteLine("Bob,25,bob@example.com");
}

// CSV 파일 읽기
using (StreamReader reader = new StreamReader(csvPath))
{
    string line;
    while ((line = reader.ReadLine()) != null)
    {
        Console.WriteLine(line);
    }
}

JSON 파일 처리 🌐

JSON은 구조화된 데이터를 저장하기에 적합하며, System.Text.Json 네임스페이스를 사용합니다.

using System.Text.Json;

string jsonPath = "data.json";

var person = new { Name = "Alice", Age = 30, Email = "alice@example.com" };

// JSON 파일 쓰기
string jsonContent = JsonSerializer.Serialize(person);
File.WriteAllText(jsonPath, jsonContent);
Console.WriteLine("JSON 파일이 작성되었습니다.");

// JSON 파일 읽기
string readJson = File.ReadAllText(jsonPath);
var deserializedPerson = JsonSerializer.Deserialize<dynamic>(readJson);
Console.WriteLine($"Name: {deserializedPerson["Name"]}");

XML 파일 처리 🛠️

C#에서는 System.Xml 네임스페이스를 활용해 XML 파일을 처리할 수 있습니다.

using System.Xml.Linq;

string xmlPath = "data.xml";

// XML 파일 쓰기
XDocument doc = new XDocument(
    new XElement("People",
        new XElement("Person",
            new XElement("Name", "Alice"),
            new XElement("Age", 30),
            new XElement("Email", "alice@example.com")
        )
    )
);
doc.Save(xmlPath);
Console.WriteLine("XML 파일이 작성되었습니다.");

// XML 파일 읽기
XDocument loadedDoc = XDocument.Load(xmlPath);
foreach (var person in loadedDoc.Descendants("Person"))
{
    Console.WriteLine($"Name: {person.Element("Name").Value}");
}

마무리 🌟

C#에서 파일과 스트림을 활용하면 데이터를 효율적으로 읽고 쓸 수 있습니다. 텍스트 파일, 바이너리 파일, 그리고 CSV, JSON, XML 같은 다양한 형식의 데이터를 처리하는 방법을 확실히 익혀두세요! 💪

잘 관리된 파일 입출력 코드는 애플리케이션의 안정성과 성능을 크게 향상시킬 수 있습니다. 특히 실무에서는 데이터 처리 효율이 핵심이니, 꾸준히 연습하고 새로운 프로젝트에 응용해 보세요. 🏆

더 나은 개발자로 성장하기 위한 작은 디딤돌, 바로 파일과 스트림 처리부터 시작입니다! 🚀

728x90
반응형