🔎 유용한 정보
1. 강의 개요
이번 강의에서는 .NET의 System.IO.Compression 네임스페이스를 활용하여
파일을 압축하고, 압축된 파일을 해제하는 애플리케이션을 제작합니다.
사용자는 하나 이상의 파일을 선택해 ZIP 형식으로 압축할 수 있으며,
ZIP 파일을 선택해 원래 파일로 해제하는 기능을 구현합니다.
2. 학습 목표
- ZipArchive 클래스를 사용해 파일 압축 및 해제 구현
- 파일 선택 및 저장 UI 구성
- 압축/해제 프로세스에 대한 오류 처리
3. 기능 요구사항
필수 기능
1️⃣ 파일 압축:
- 사용자가 선택한 파일을 ZIP 파일로 압축
2️⃣ 파일 해제:
- 사용자가 선택한 ZIP 파일을 압축 해제
3️⃣ UI 구성 및 동작:
- 직관적인 버튼 기반 압축/해제 UI 구성
4. 실습: 파일 압축 및 해제 애플리케이션 제작
1️⃣ 폼 구성
- 폼(Form) 이름: Form1
- 컨트롤 배치:
컨트롤 타입 이름 위치 크기
Button | btnCompress | 폼 상단 왼쪽 | (100 x 30) |
Button | btnExtract | 폼 상단 오른쪽 | (100 x 30) |
Label | lblStatus | 폼 하단 전체 | (400 x 30) |
📌 폼 디자인 예시:
--------------------------------------------------
| [Compress 버튼] [Extract 버튼] |
--------------------------------------------------
| [Status Label - 진행 상태 표시] |
--------------------------------------------------
2️⃣ 코드 작성
(1) 파일 압축 기능
using System;
using System.IO;
using System.IO.Compression;
using System.Windows.Forms;
namespace WindowsFormsApp_Zip
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// 파일 압축
private void btnCompress_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Multiselect = true; // 여러 파일 선택 가능
openFileDialog.Filter = "모든 파일 (*.*)|*.*";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "ZIP 파일 (*.zip)|*.zip";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string zipFilePath = saveFileDialog.FileName;
CompressFiles(openFileDialog.FileNames, zipFilePath);
}
}
}
}
}
private void CompressFiles(string[] filePaths, string zipFilePath)
{
try
{
using (var zipStream = new FileStream(zipFilePath, FileMode.Create))
{
using (var archive = new ZipArchive(zipStream, ZipArchiveMode.Create))
{
foreach (var filePath in filePaths)
{
string fileName = Path.GetFileName(filePath);
var entry = archive.CreateEntryFromFile(filePath, fileName);
}
}
}
lblStatus.Text = "파일이 성공적으로 압축되었습니다.";
}
catch (Exception ex)
{
lblStatus.Text = $"압축 중 오류 발생: {ex.Message}";
}
}
}
}
(2) 파일 해제 기능
// 파일 압축 해제
private void btnExtract_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "ZIP 파일 (*.zip)|*.zip";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
using (FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog())
{
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
string extractPath = folderBrowserDialog.SelectedPath;
ExtractFiles(openFileDialog.FileName, extractPath);
}
}
}
}
}
private void ExtractFiles(string zipFilePath, string extractPath)
{
try
{
ZipFile.ExtractToDirectory(zipFilePath, extractPath);
lblStatus.Text = "파일이 성공적으로 압축 해제되었습니다.";
}
catch (Exception ex)
{
lblStatus.Text = $"압축 해제 중 오류 발생: {ex.Message}";
}
}
(3) Designer 코드
private void InitializeComponent()
{
this.btnCompress = new Button();
this.btnExtract = new Button();
this.lblStatus = new Label();
// Compress Button 설정
this.btnCompress.Location = new System.Drawing.Point(10, 10);
this.btnCompress.Size = new System.Drawing.Size(100, 30);
this.btnCompress.Text = "Compress";
this.btnCompress.Click += new EventHandler(this.btnCompress_Click);
// Extract Button 설정
this.btnExtract.Location = new System.Drawing.Point(120, 10);
this.btnExtract.Size = new System.Drawing.Size(100, 30);
this.btnExtract.Text = "Extract";
this.btnExtract.Click += new EventHandler(this.btnExtract_Click);
// Status Label 설정
this.lblStatus.Location = new System.Drawing.Point(10, 50);
this.lblStatus.Size = new System.Drawing.Size(400, 30);
this.lblStatus.Text = "상태: 준비 완료";
// Form 설정
this.ClientSize = new System.Drawing.Size(400, 100);
this.Controls.Add(this.btnCompress);
this.Controls.Add(this.btnExtract);
this.Controls.Add(this.lblStatus);
this.Text = "파일 압축 및 해제";
}
3️⃣ 실행 결과
1️⃣ 파일 압축
- "Compress" 버튼 클릭 → OpenFileDialog로 파일 선택 → SaveFileDialog에서 ZIP 파일 저장
2️⃣ 파일 해제
- "Extract" 버튼 클릭 → OpenFileDialog에서 ZIP 파일 선택 → FolderBrowserDialog에서 저장 경로 선택
3️⃣ 진행 상태 표시
- Label로 작업 성공 또는 오류 메시지 표시
5. 주요 개념 요약
- ZipArchive: ZIP 파일 생성 및 관리
- CreateEntryFromFile: 파일을 ZIP 항목으로 추가
- ZipFile.ExtractToDirectory: ZIP 파일 압축 해제
- OpenFileDialog, SaveFileDialog, FolderBrowserDialog: 파일 및 폴더 선택 대화 상자
📌 #CSharp #WindowsForms #ZipArchive #파일압축 #파일해제 #OpenFileDialog
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 93편: 멀티스레드를 활용한 백그라운드 작업 처리 (0) | 2025.05.07 |
---|---|
C# Windows Forms 강의 91편: SMTP를 활용한 이메일 전송 애플리케이션 제작 (0) | 2025.05.05 |
C# Windows Forms 강의 90편: Excel 파일 다루기 - NPOI 라이브러리를 활용한 데이터 읽기 및 쓰기 (0) | 2025.05.04 |
C# Windows Forms 강의 89편: 그래프 그리기 애플리케이션 제작 - 실시간 데이터 시각화 (0) | 2025.05.03 |
C# Windows Forms 강의 88편: 멀티미디어 플레이어 제작 - 오디오 및 비디오 재생 기능 구현 (0) | 2025.05.02 |
🔎 유용한 정보