반응형
1. 강의 개요
이번 강의에서는 OpenFileDialog와 SaveFileDialog를 사용하여 파일 열기 및 저장 기능을 구현합니다.
텍스트 파일을 읽고 쓰는 간단한 텍스트 에디터를 제작하며, 파일 다이얼로그의 고급 옵션을 활용합니다.
2. 학습 목표
- OpenFileDialog와 SaveFileDialog의 주요 속성과 동작 방식 학습.
- 파일 열기 및 저장 기능 구현.
- 파일 필터와 사용자 환경 개선을 위한 고급 옵션 활용.
3. OpenFileDialog와 SaveFileDialog 개요
OpenFileDialog란?
사용자에게 파일 열기 창을 제공하는 Windows Forms 컨트롤.
- 사용자가 선택한 파일 경로를 반환.
- 텍스트 파일, 이미지 파일 등 특정 파일 형식을 필터링 가능.
SaveFileDialog란?
사용자에게 파일 저장 창을 제공하는 Windows Forms 컨트롤.
- 사용자가 저장할 파일의 경로와 이름을 입력하도록 요청.
- 파일 확장자 필터링 및 덮어쓰기 경고 제공.
주요 속성
속성 설명 예제
Filter | 파일 형식 필터 | `"텍스트 파일 (*.txt) |
InitialDirectory | 초기 디렉터리 경로 설정 | openFileDialog1.InitialDirectory = @"C:\"; |
FileName | 선택된 파일 이름 | string filePath = openFileDialog1.FileName; |
Title | 다이얼로그 제목 | openFileDialog1.Title = "파일 열기"; |
OverwritePrompt | 덮어쓰기 경고 표시 여부 | saveFileDialog1.OverwritePrompt = true; |
4. 실습: 파일 열기 및 저장 기능 구현
요구사항
- OpenFileDialog로 텍스트 파일 열기 기능 구현.
- SaveFileDialog로 텍스트 파일 저장 기능 구현.
- 텍스트 박스를 사용해 파일 내용을 표시 및 편집.
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
TextBox | txtEditor | (빈 상태) | 중앙 | (350 x 200) |
Button | btnOpen | "파일 열기" | 하단 왼쪽 | (100 x 30) |
Button | btnSave | "파일 저장" | 하단 오른쪽 | (100 x 30) |
코드 작성
Form1.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
InitializeFileDialog();
}
private void InitializeFileDialog()
{
// "파일 열기" 버튼 클릭 이벤트 연결
btnOpen.Click += BtnOpen_Click;
// "파일 저장" 버튼 클릭 이벤트 연결
btnSave.Click += BtnSave_Click;
}
// "파일 열기" 버튼 클릭 이벤트
private void BtnOpen_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
openFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
openFileDialog.Title = "파일 열기";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
txtEditor.Text = File.ReadAllText(filePath); // 파일 내용 읽기
}
}
}
// "파일 저장" 버튼 클릭 이벤트
private void BtnSave_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
saveFileDialog.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
saveFileDialog.Title = "파일 저장";
saveFileDialog.OverwritePrompt = true;
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
File.WriteAllText(filePath, txtEditor.Text); // 파일 저장
MessageBox.Show("파일이 저장되었습니다.", "알림");
}
}
}
}
}
Form1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
private TextBox txtEditor;
private Button btnOpen;
private Button btnSave;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.txtEditor = new TextBox();
this.btnOpen = new Button();
this.btnSave = new Button();
this.SuspendLayout();
// txtEditor
this.txtEditor.Location = new System.Drawing.Point(20, 20);
this.txtEditor.Multiline = true;
this.txtEditor.Name = "txtEditor";
this.txtEditor.ScrollBars = ScrollBars.Vertical;
this.txtEditor.Size = new System.Drawing.Size(350, 200);
this.txtEditor.TabIndex = 0;
// btnOpen
this.btnOpen.Location = new System.Drawing.Point(20, 240);
this.btnOpen.Name = "btnOpen";
this.btnOpen.Size = new System.Drawing.Size(100, 30);
this.btnOpen.Text = "파일 열기";
this.btnOpen.UseVisualStyleBackColor = true;
// btnSave
this.btnSave.Location = new System.Drawing.Point(270, 240);
this.btnSave.Name = "btnSave";
this.btnSave.Size = new System.Drawing.Size(100, 30);
this.btnSave.Text = "파일 저장";
this.btnSave.UseVisualStyleBackColor = true;
// Form1
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(400, 300);
this.Controls.Add(this.btnSave);
this.Controls.Add(this.btnOpen);
this.Controls.Add(this.txtEditor);
this.Name = "Form1";
this.Text = "파일 열기 및 저장 예제";
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
5. 실행 결과
- 초기 상태
- 텍스트 박스는 비어 있으며, "파일 열기"와 "파일 저장" 버튼이 표시됩니다.
- 파일 열기
- "파일 열기" 버튼 클릭 → OpenFileDialog가 표시됩니다.
- 파일 선택 후 "열기" 버튼 클릭 → 선택한 파일의 내용이 텍스트 박스에 표시됩니다.
- 파일 저장
- 텍스트 박스에 내용을 입력 후 "파일 저장" 버튼 클릭 → SaveFileDialog가 표시됩니다.
- 파일 이름과 경로를 입력 후 "저장" 버튼 클릭 → 입력한 내용이 파일에 저장됩니다.
- 파일 필터
- OpenFileDialog와 SaveFileDialog에서 .txt 파일만 표시되며, 필터를 변경하면 모든 파일(.)도 표시됩니다.
6. 주요 개념 요약
- OpenFileDialog와 SaveFileDialog
- 파일 열기와 저장 다이얼로그를 활용해 사용자 친화적인 파일 관리 구현.
- Filter, InitialDirectory, OverwritePrompt 등 다양한 속성을 설정하여 사용자 경험 개선.
- 파일 읽기와 쓰기
- File.ReadAllText로 파일 읽기, File.WriteAllText로 파일 쓰기 구현.
- 응용 프로그램과 파일의 연동
- 사용자 입력 데이터를 파일로 저장하거나, 파일 데이터를 프로그램에 불러오는 작업 가능.
반응형
'📁 [4] 개발자 정보 & 코드 노트 > C#' 카테고리의 다른 글
C# Windows Forms 강의 47편: 폼 간 데이터 전달 방법 (0) | 2025.03.22 |
---|---|
C# Windows Forms 강의 46편: BackgroundWorker로 비동기 작업 처리 (0) | 2025.03.21 |
C# Windows Forms 강의 44편: Timer와 GDI+를 활용한 간단한 애니메이션 효과 (0) | 2025.03.19 |
C# Windows Forms 강의 43편: Drag & Drop 기능 구현 (0) | 2025.03.18 |
C# Windows Forms 강의 42편: UserControl로 복잡한 UI 구성 (1) | 2025.03.17 |