728x90
반응형
반응형

앞서 배운 내용을 종합해서 이번에는 C#으로 간단한 파일 관리 프로그램을 만들어봅니다.
이 프로젝트를 통해 클래스, 메서드, 예외처리, 파일 입출력, 비동기 처리까지 실제로 적용해볼 수 있습니다.


1. 프로젝트 목표

  • 특정 폴더의 모든 파일 목록 읽기
  • 파일 이름, 크기 출력하기
  • 파일 복사 기능 추가하기 (비동기)
  • 파일 삭제 기능 추가하기

2. 기본 구조 설계

 FileManager 클래스 만들기

using System;
using System.IO;
using System.Threading.Tasks;

public class FileManager
{
    private string _directoryPath;

    public FileManager(string directoryPath)
    {
        _directoryPath = directoryPath;
    }

    public void ListFiles()
    {
        try
        {
            if (!Directory.Exists(_directoryPath))
            {
                Console.WriteLine("디렉토리가 존재하지 않습니다.");
                return;
            }

            string[] files = Directory.GetFiles(_directoryPath);
            foreach (string file in files)
            {
                FileInfo fi = new FileInfo(file);
                Console.WriteLine($"{fi.Name} - {fi.Length} bytes");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("파일 목록 조회 실패: " + ex.Message);
        }
    }

    public async Task CopyFileAsync(string sourceFileName, string destFileName)
    {
        try
        {
            string sourcePath = Path.Combine(_directoryPath, sourceFileName);
            string destPath = Path.Combine(_directoryPath, destFileName);

            if (!File.Exists(sourcePath))
            {
                Console.WriteLine("원본 파일이 존재하지 않습니다.");
                return;
            }

            using (FileStream sourceStream = File.Open(sourcePath, FileMode.Open))
            using (FileStream destStream = File.Create(destPath))
            {
                await sourceStream.CopyToAsync(destStream);
            }

            Console.WriteLine("파일 복사 완료!");
        }
        catch (Exception ex)
        {
            Console.WriteLine("파일 복사 실패: " + ex.Message);
        }
    }

    public void DeleteFile(string fileName)
    {
        try
        {
            string filePath = Path.Combine(_directoryPath, fileName);

            if (File.Exists(filePath))
            {
                File.Delete(filePath);
                Console.WriteLine("파일 삭제 완료!");
            }
            else
            {
                Console.WriteLine("파일이 존재하지 않습니다.");
            }
        }
        catch (Exception ex)
        {
            Console.WriteLine("파일 삭제 실패: " + ex.Message);
        }
    }
}

3. 프로그램 실행 예제

static async Task Main(string[] args)
{
    FileManager manager = new FileManager("C:\\TestFolder");

    Console.WriteLine("1. 파일 목록 보기");
    Console.WriteLine("2. 파일 복사");
    Console.WriteLine("3. 파일 삭제");
    Console.Write("선택: ");
    int choice = int.Parse(Console.ReadLine());

    switch (choice)
    {
        case 1:
            manager.ListFiles();
            break;
        case 2:
            Console.Write("복사할 파일 이름: ");
            string src = Console.ReadLine();
            Console.Write("새 파일 이름: ");
            string dst = Console.ReadLine();
            await manager.CopyFileAsync(src, dst);
            break;
        case 3:
            Console.Write("삭제할 파일 이름: ");
            string del = Console.ReadLine();
            manager.DeleteFile(del);
            break;
        default:
            Console.WriteLine("잘못된 선택입니다.");
            break;
    }
}

 

이 미니 프로젝트를 통해

  • 파일 입출력
  • 예외 처리
  • 클래스와 메서드 구조화
  • 비동기 프로그래밍(async/await) 을 실제로 경험할 수 있었습니다.

작고 단순한 프로그램부터 차근차근 만들다 보면 실력이 빠르게 늘어납니다!

 

728x90
반응형
728x90
반응형
반응형

프로그래밍에서는 예상하지 못한 문제가 항상 발생할 수 있습니다.
C#에서는 예외(Exception) 처리를 통해 프로그램이 갑자기 종료되는 것을 막고,
파일 입출력(File IO) 기능으로 파일을 읽고 쓸 수 있습니다.

이번 글에서는 try-catch-finally 구조와, 파일을 읽고 쓰는 기본 방법을 정리해봅니다.


1. 예외 처리 (Exception Handling)

 try-catch-finally 구조

try
{
    // 예외가 발생할 수 있는 코드
    int x = int.Parse("not a number");
}
catch (FormatException ex)
{
    Console.WriteLine("형식이 잘못되었습니다: " + ex.Message);
}
catch (Exception ex)
{
    Console.WriteLine("오류 발생: " + ex.Message);
}
finally
{
    Console.WriteLine("무조건 실행되는 블록");
}
  • try: 예외가 발생할 수 있는 코드를 감쌈
  • catch: 예외가 발생하면 실행됨
  • finally: 예외 발생 여부와 관계없이 항상 실행

 여러 catch 사용하기

특정 예외만 따로 처리할 수 있습니다.

catch (IOException ex)
{
    Console.WriteLine("파일 입출력 오류: " + ex.Message);
}
catch (NullReferenceException ex)
{
    Console.WriteLine("널 참조 오류: " + ex.Message);
}

 throw로 직접 예외 던지기

throw new Exception("문제가 발생했습니다!");

2. 파일 입출력 (File IO)

 파일에 쓰기

using System.IO;

File.WriteAllText("sample.txt", "Hello, World!");
  • 지정한 파일에 문자열을 기록합니다.
  • 파일이 없으면 새로 생성, 있으면 덮어쓰기

 파일에서 읽기

string content = File.ReadAllText("sample.txt");
Console.WriteLine(content);
  • 파일 내용을 한 번에 읽어 문자열로 반환합니다.

 줄 단위로 읽고 쓰기

// 여러 줄 쓰기
string[] lines = { "첫 번째 줄", "두 번째 줄", "세 번째 줄" };
File.WriteAllLines("lines.txt", lines);

// 여러 줄 읽기
string[] readLines = File.ReadAllLines("lines.txt");
foreach (string line in readLines)
{
    Console.WriteLine(line);
}

3. 실전 예제: 파일 읽고 없으면 새로 만들기

string path = "data.txt";

try
{
    if (!File.Exists(path))
    {
        File.WriteAllText(path, "초기 데이터");
    }

    string text = File.ReadAllText(path);
    Console.WriteLine("파일 내용:");
    Console.WriteLine(text);
}
catch (Exception ex)
{
    Console.WriteLine("오류 발생: " + ex.Message);
}

이번 글에서는

  • try-catch-finally를 통한 예외 처리 방법
  • File 클래스를 이용한 파일 읽고 쓰기 방법 을 정리했습니다.

안전한 코드 작성파일 기반 데이터 처리는 모든 프로그램에서 기본이 되는 기술입니다.

 

728x90
반응형

+ Recent posts