[C#] WinForms로 파일 관리 앱 만들기 1탄

2025. 4. 18. 14:17개발이야기

728x90
반응형

GUI 기초 프로젝트

지난 글에서는 콘솔 기반 파일 관리 도구를 만들었습니다.
이번에는 C# WinForms를 이용해 GUI(그래픽 사용자 인터페이스) 형태로 파일 관리 앱을 만들어보겠습니다!

WinForms는 데스크탑 앱을 간단하게 만들 수 있는 프레임워크로, 초보자에게 매우 친숙합니다.


1. 프로젝트 목표

  • 폴더 경로를 입력 받아 파일 목록 출력
  • 파일 복사 버튼
  • 파일 삭제 버튼

2. 기본 설계

 폼 구성

  • TextBox: 폴더 경로 입력
  • Button: 파일 목록 새로고침
  • ListBox: 파일 목록 표시
  • TextBox: 선택된 파일 이름 입력
  • Button: 파일 복사
  • Button: 파일 삭제

3. 코드 작성하기

 폼 디자이너 예시

(Visual Studio에서 끌어다 놓기만 하면 됩니다)

  • TextBox (Name: txtFolderPath)
  • Button (Name: btnLoadFiles, Text: "파일 불러오기")
  • ListBox (Name: listBoxFiles)
  • TextBox (Name: txtFileName)
  • Button (Name: btnCopyFile, Text: "복사")
  • Button (Name: btnDeleteFile, Text: "삭제")

 코드 예제

using System;
using System.IO;
using System.Threading.Tasks;
using System.Windows.Forms;

public partial class MainForm : Form
{
    public MainForm()
    {
        InitializeComponent();
    }

    private void btnLoadFiles_Click(object sender, EventArgs e)
    {
        listBoxFiles.Items.Clear();
        string folderPath = txtFolderPath.Text;

        if (!Directory.Exists(folderPath))
        {
            MessageBox.Show("폴더가 존재하지 않습니다.");
            return;
        }

        string[] files = Directory.GetFiles(folderPath);
        listBoxFiles.Items.AddRange(files);
    }

    private async void btnCopyFile_Click(object sender, EventArgs e)
    {
        string folderPath = txtFolderPath.Text;
        string fileName = txtFileName.Text;

        string sourcePath = Path.Combine(folderPath, fileName);
        string destPath = Path.Combine(folderPath, "복사본_" + fileName);

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

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

        MessageBox.Show("파일 복사 완료!");
        btnLoadFiles.PerformClick(); // 목록 새로고침
    }

    private void btnDeleteFile_Click(object sender, EventArgs e)
    {
        string folderPath = txtFolderPath.Text;
        string fileName = txtFileName.Text;
        string filePath = Path.Combine(folderPath, fileName);

        if (!File.Exists(filePath))
        {
            MessageBox.Show("파일이 존재하지 않습니다.");
            return;
        }

        File.Delete(filePath);
        MessageBox.Show("파일 삭제 완료!");
        btnLoadFiles.PerformClick(); // 목록 새로고침
    }
}

5. 주요 포인트

항목 설명

파일 목록 표시 ListBox.Items.AddRange() 사용
비동기 복사 CopyToAsync로 복사 중에도 UI 멈추지 않게 함
버튼 이벤트 연결 Designer 창에서 각 버튼의 Click 이벤트 연결
사용자 입력 검증 파일 존재 여부를 항상 체크

 마무리

이번 글에서는 C# WinForms를 사용해 기본적인 파일 관리 GUI 앱을 만들어봤습니다.

  • 폴더 탐색
  • 파일 복사
  • 파일 삭제
  • 비동기 처리로 UI 멈춤 방지

WinForms는 초보자도 빠르게 앱을 만들어 볼 수 있어 C# 학습에 매우 좋은 선택지입니다!

 

728x90
반응형