🔎 유용한 정보
1. 강의 개요
이번 강의에서는 Windows Forms를 활용해 파일 관리 애플리케이션을 제작합니다.
사용자는 특정 디렉터리를 탐색하고,
해당 디렉터리에서 원하는 파일을 검색하거나 삭제할 수 있습니다.
Windows Forms의 TreeView와 ListView 컨트롤을 사용하여
파일 탐색기와 유사한 인터페이스를 구현합니다.
2. 학습 목표
- TreeView를 사용해 디렉터리 구조 탐색
- ListView를 사용해 파일 목록 표시
- 파일 검색 및 삭제 기능 구현
- 사용자 친화적인 파일 관리 UI 제작
3. 기능 요구사항
필수 기능
1️⃣ 디렉터리 탐색:
- TreeView를 사용하여 폴더 구조 표시
2️⃣ 파일 목록 표시:
- 선택된 디렉터리의 파일을 ListView에 표시
3️⃣ 파일 검색 및 삭제:
- 사용자가 입력한 키워드로 파일 검색 및 삭제
4️⃣ UI 구성 및 동작:
- TreeView와 ListView를 활용한 탐색기 UI 구성
4. 실습: 파일 관리 애플리케이션 제작
1️⃣ 폼 구성
- 폼(Form) 이름: Form1
- 컨트롤 배치:
컨트롤 타입 이름 위치 크기
TreeView | treeViewDirs | 폼 왼쪽 | (200 x 400) |
ListView | listViewFiles | 폼 오른쪽 상단 | (400 x 300) |
TextBox | txtSearch | 폼 오른쪽 하단 왼쪽 | (300 x 30) |
Button | btnSearch | 폼 오른쪽 하단 중앙 | (100 x 30) |
Button | btnDelete | 폼 오른쪽 하단 오른쪽 | (100 x 30) |
📌 폼 디자인 예시:
--------------------------------------------------
| [TreeView - 디렉터리 구조] [ListView - 파일 목록] |
--------------------------------------------------
| [Search TextBox] [Search] [Delete]|
--------------------------------------------------
2️⃣ 코드 작성
(1) 디렉터리 탐색 및 파일 목록 표시
using System;
using System.IO;
using System.Linq;
using System.Windows.Forms;
namespace WindowsFormsApp_FileManager
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
LoadDrives();
}
// 드라이브 로드
private void LoadDrives()
{
treeViewDirs.Nodes.Clear();
var drives = DriveInfo.GetDrives();
foreach (var drive in drives)
{
var driveNode = new TreeNode(drive.Name) { Tag = drive.Name };
treeViewDirs.Nodes.Add(driveNode);
LoadDirectories(driveNode);
}
}
// 디렉터리 로드
private void LoadDirectories(TreeNode node)
{
try
{
string path = node.Tag.ToString();
var directories = Directory.GetDirectories(path);
foreach (var directory in directories)
{
var directoryNode = new TreeNode(Path.GetFileName(directory)) { Tag = directory };
node.Nodes.Add(directoryNode);
}
}
catch { /* 접근 권한 에러 무시 */ }
}
// 디렉터리 선택 시 파일 표시
private void treeViewDirs_AfterSelect(object sender, TreeViewEventArgs e)
{
string selectedPath = e.Node.Tag.ToString();
LoadFiles(selectedPath);
}
// 파일 로드
private void LoadFiles(string path)
{
try
{
listViewFiles.Items.Clear();
var files = Directory.GetFiles(path);
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
var item = new ListViewItem(fileInfo.Name)
{
Tag = fileInfo.FullName
};
item.SubItems.Add(fileInfo.Length.ToString());
item.SubItems.Add(fileInfo.LastWriteTime.ToString());
listViewFiles.Items.Add(item);
}
}
catch { /* 접근 권한 에러 무시 */ }
}
}
}
(2) 파일 검색 및 삭제
// 파일 검색
private void btnSearch_Click(object sender, EventArgs e)
{
string searchKeyword = txtSearch.Text.Trim();
if (string.IsNullOrEmpty(searchKeyword))
{
MessageBox.Show("검색어를 입력하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
string currentPath = treeViewDirs.SelectedNode?.Tag.ToString();
if (string.IsNullOrEmpty(currentPath))
{
MessageBox.Show("디렉터리를 선택하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
try
{
listViewFiles.Items.Clear();
var files = Directory.GetFiles(currentPath, $"*{searchKeyword}*");
foreach (var file in files)
{
var fileInfo = new FileInfo(file);
var item = new ListViewItem(fileInfo.Name)
{
Tag = fileInfo.FullName
};
item.SubItems.Add(fileInfo.Length.ToString());
item.SubItems.Add(fileInfo.LastWriteTime.ToString());
listViewFiles.Items.Add(item);
}
}
catch
{
MessageBox.Show("검색 중 오류가 발생했습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
// 파일 삭제
private void btnDelete_Click(object sender, EventArgs e)
{
if (listViewFiles.SelectedItems.Count == 0)
{
MessageBox.Show("삭제할 파일을 선택하세요.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
return;
}
var confirmResult = MessageBox.Show("선택한 파일을 삭제하시겠습니까?", "확인", MessageBoxButtons.YesNo, MessageBoxIcon.Question);
if (confirmResult == DialogResult.Yes)
{
try
{
foreach (ListViewItem item in listViewFiles.SelectedItems)
{
string filePath = item.Tag.ToString();
File.Delete(filePath);
listViewFiles.Items.Remove(item);
}
MessageBox.Show("파일이 삭제되었습니다.", "완료", MessageBoxButtons.OK, MessageBoxIcon.Information);
}
catch
{
MessageBox.Show("파일 삭제 중 오류가 발생했습니다.", "오류", MessageBoxButtons.OK, MessageBoxIcon.Error);
}
}
}
(3) Designer 코드
private void InitializeComponent()
{
this.treeViewDirs = new TreeView();
this.listViewFiles = new ListView();
this.txtSearch = new TextBox();
this.btnSearch = new Button();
this.btnDelete = new Button();
// TreeView 설정
this.treeViewDirs.Location = new System.Drawing.Point(10, 10);
this.treeViewDirs.Size = new System.Drawing.Size(200, 400);
this.treeViewDirs.AfterSelect += new TreeViewEventHandler(this.treeViewDirs_AfterSelect);
// ListView 설정
this.listViewFiles.Location = new System.Drawing.Point(220, 10);
this.listViewFiles.Size = new System.Drawing.Size(400, 300);
this.listViewFiles.View = View.Details;
this.listViewFiles.Columns.Add("파일 이름", 150);
this.listViewFiles.Columns.Add("크기", 100);
this.listViewFiles.Columns.Add("수정 날짜", 150);
// Search TextBox 설정
this.txtSearch.Location = new System.Drawing.Point(220, 320);
this.txtSearch.Size = new System.Drawing.Size(300, 30);
// Search Button 설정
this.btnSearch.Location = new System.Drawing.Point(530, 320);
this.btnSearch.Size = new System.Drawing.Size(80, 30);
this.btnSearch.Text = "Search";
this.btnSearch.Click += new EventHandler(this.btnSearch_Click);
// Delete Button 설정
this.btnDelete.Location = new System.Drawing.Point(620, 320);
this.btnDelete.Size = new System.Drawing.Size(80, 30);
this.btnDelete.Text = "Delete";
this.btnDelete.Click += new EventHandler(this.btnDelete_Click);
// Form 설정
this.ClientSize = new System.Drawing.Size(720, 400);
this.Controls.Add(this.treeViewDirs);
this.Controls.Add(this.listViewFiles);
this.Controls.Add(this.txtSearch);
this.Controls.Add(this.btnSearch);
this.Controls.Add(this.btnDelete);
this.Text = "파일 관리 애플리케이션";
}
3️⃣ 실행 결과
1️⃣ 디렉터리 탐색
- TreeView에서 폴더 선택 → ListView에 해당 디렉터리의 파일 표시
2️⃣ 파일 검색
- TextBox에 키워드 입력 → "Search" 클릭 → ListView에 검색된 파일 표시
3️⃣ 파일 삭제
- ListView에서 파일 선택 → "Delete" 클릭 → 선택된 파일 삭제
5. 주요 개념 요약
- TreeView: 디렉터리 구조를 계층적으로 표시
- ListView: 디렉터리 내 파일 목록을 상세히 표시
- FileInfo: 파일의 세부 정보(크기, 수정 날짜 등) 제공
- Directory.GetFiles: 특정 디렉터리에서 파일 목록 검색
📌 #CSharp #WindowsForms #파일관리 #TreeView #ListView #FileManagement
'Study > C#' 카테고리의 다른 글
C# Windows Forms 강의 87편: 실시간 채팅 애플리케이션 제작 - TCP 소켓 통신 활용 (0) | 2025.05.01 |
---|---|
C# Windows Forms 강의 85편: 데이터베이스 연동 애플리케이션 - SQL Server를 활용한 CRUD 구현 (0) | 2025.04.30 |
C# Windows Forms 강의 83편: 스케줄 관리 애플리케이션 제작 - 캘린더 및 알림 기능 구현 (0) | 2025.04.28 |
C# Windows Forms 강의 82편: 자연어 처리 기반 채팅봇 제작 - ChatGPT API 활용 (0) | 2025.04.27 |
C# Windows Forms 강의 81편: AI 기반 객체 탐지 및 추적 - YOLO 모델 활용 (0) | 2025.04.26 |
🔎 유용한 정보