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#을 제대로 쓰려면 반드시 익혀야 하는 두 가지: 메서드와 클래스입니다.
이 글에서는 함수를 어떻게 정의하고 호출하는지, 클래스와 객체를 어떻게 사용하는지, 그리고 기본적인 캡슐화까지 간단한 예제와 함께 정리해봅니다.


1. 메서드 (Method)란?

메서드는 어떤 동작(기능)을 수행하는 코드 블록입니다.
한 번 정의해두면, 여러 번 호출할 수 있어 재사용성이 높고 가독성도 좋아집니다.

 기본 형태

리턴형 메서드이름(매개변수들)
{
    // 실행 코드
    return 결과값;
}

 예제: 두 수 더하기

int Add(int a, int b)
{
    return a + b;
}

// 호출
int result = Add(3, 5);
Console.WriteLine(result);  // 8

 void 메서드

리턴값이 없을 때는 void를 사용합니다.

void SayHello(string name)
{
    Console.WriteLine($"안녕하세요, {name}님");
}

2.  클래스 (Class)란?

클래스는 **데이터(변수)와 동작(메서드)**를 묶어놓은 구조입니다.
C#은 객체지향 언어이므로, 모든 프로그램은 클래스를 중심으로 구성됩니다.

 클래스 예제

class Person
{
    // 필드 (속성)
    public string Name;
    public int Age;

    // 메서드
    public void Introduce()
    {
        Console.WriteLine($"저는 {Name}, {Age}살입니다.");
    }
}

 객체 생성 및 사용

Person p = new Person();
p.Name = "홍길동";
p.Age = 25;
p.Introduce();

3.  접근 제한자 (Access Modifier)

  • public: 어디서나 접근 가능
  • private: 클래스 내부에서만 접근 가능
  • protected: 상속받은 클래스에서 접근 가능
  • internal: 같은 프로젝트 내에서만 접근 가능

대부분 기본적으로 private이고, 외부에 노출할 필드나 메서드에만 public을 사용합니다.


4. 생성자 (Constructor)

클래스가 생성될 때 자동으로 호출되는 특수한 메서드입니다.

class Dog
{
    public string Name;

    // 생성자
    public Dog(string name)
    {
        Name = name;
    }

    public void Bark()
    {
        Console.WriteLine($"{Name}가 멍멍 짖습니다!");
    }
}

// 사용
Dog d = new Dog("초코");
d.Bark();

 예제 정리

class Calculator
{
    public int Add(int x, int y) => x + y;
    public int Sub(int x, int y) => x - y;
}

// 사용
Calculator calc = new Calculator();
int sum = calc.Add(10, 5);
int diff = calc.Sub(10, 5);
Console.WriteLine($"합: {sum}, 차: {diff}");

 

이번 글에서는 C#의 핵심 개념 중 하나인 메서드와 클래스에 대해 정리해보았습니다.
이 두 가지를 이해하면 객체지향 구조로 코드를 더 체계적으로 짤 수 있게 됩니다.

 

728x90
반응형

+ Recent posts