728x90
1. 강의 개요
이번 강의에서는 Windows Forms에서 OpenFileDialog와 SaveFileDialog를 사용해 파일을 열고 저장하는 방법을 학습합니다.
이 두 대화 상자는 사용자가 파일을 선택하거나 저장할 수 있도록 편리한 인터페이스를 제공합니다.
2. 학습 목표
- OpenFileDialog를 사용해 파일 선택 및 내용 읽기.
- SaveFileDialog를 사용해 텍스트 파일 저장.
- TextBox와 연동해 파일의 내용을 표시 및 수정.
3. OpenFileDialog와 SaveFileDialog란?
OpenFileDialog
- 파일 열기 대화 상자를 표시하여 사용자가 파일을 선택할 수 있도록 함.
- 선택한 파일의 경로와 이름을 가져와 읽을 수 있음.
SaveFileDialog
- 파일 저장 대화 상자를 표시하여 사용자가 파일을 저장할 경로와 이름을 지정할 수 있음.
주요 속성 및 메서드
속성/메서드 설명 예제
Filter | 파일 필터 설정 (예: *.txt, *.csv) | `openFileDialog.Filter = "텍스트 파일 |
FileName | 선택된 파일 이름 | string fileName = openFileDialog.FileName; |
ShowDialog() | 대화 상자를 열고 결과 반환 (OK or Cancel) | if (openFileDialog.ShowDialog() == DialogResult.OK) |
4. 실습: OpenFileDialog와 SaveFileDialog로 파일 열기 및 저장 구현
요구사항
- OpenFileDialog로 파일을 선택하여 내용을 읽어 TextBox에 표시.
- SaveFileDialog로 TextBox 내용을 파일로 저장.
- Label에 현재 열려 있는 파일 경로 표시.
폼 구성
컨트롤 타입 이름 텍스트 위치 크기
Label | lblFilePath | "파일 경로: (없음)" | 상단 | (400 x 30) |
TextBox | txtContent | (없음) | 중간 | (400 x 200) |
Button | btnOpenFile | "파일 열기" | 하단 왼쪽 | (150 x 30) |
Button | btnSaveFile | "파일 저장" | 하단 오른쪽 | (150 x 30) |
코드 작성
Form1.cs
using System;
using System.IO;
using System.Windows.Forms;
namespace WindowsFormsApp1
{
public partial class Form1 : Form
{
public Form1()
{
InitializeComponent();
}
// "파일 열기" 버튼 클릭 이벤트
private void BtnOpenFile_Click(object sender, EventArgs e)
{
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
openFileDialog.Title = "파일 열기";
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = openFileDialog.FileName;
lblFilePath.Text = $"파일 경로: {filePath}";
try
{
string fileContent = File.ReadAllText(filePath);
txtContent.Text = fileContent;
}
catch (Exception ex)
{
MessageBox.Show($"파일을 읽는 중 오류가 발생했습니다: {ex.Message}", "오류");
}
}
}
}
// "파일 저장" 버튼 클릭 이벤트
private void BtnSaveFile_Click(object sender, EventArgs e)
{
using (SaveFileDialog saveFileDialog = new SaveFileDialog())
{
saveFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
saveFileDialog.Title = "파일 저장";
if (saveFileDialog.ShowDialog() == DialogResult.OK)
{
string filePath = saveFileDialog.FileName;
try
{
File.WriteAllText(filePath, txtContent.Text);
lblFilePath.Text = $"저장된 파일 경로: {filePath}";
MessageBox.Show("파일이 성공적으로 저장되었습니다.", "파일 저장");
}
catch (Exception ex)
{
MessageBox.Show($"파일을 저장하는 중 오류가 발생했습니다: {ex.Message}", "오류");
}
}
}
}
}
}
Form1.Designer.cs
namespace WindowsFormsApp1
{
partial class Form1
{
private System.ComponentModel.IContainer components = null;
private Label lblFilePath;
private TextBox txtContent;
private Button btnOpenFile;
private Button btnSaveFile;
protected override void Dispose(bool disposing)
{
if (disposing && (components != null))
{
components.Dispose();
}
base.Dispose(disposing);
}
private void InitializeComponent()
{
this.lblFilePath = new Label();
this.txtContent = new TextBox();
this.btnOpenFile = new Button();
this.btnSaveFile = new Button();
this.SuspendLayout();
// lblFilePath
this.lblFilePath.AutoSize = true;
this.lblFilePath.Location = new System.Drawing.Point(20, 20);
this.lblFilePath.Name = "lblFilePath";
this.lblFilePath.Size = new System.Drawing.Size(150, 20);
this.lblFilePath.TabIndex = 0;
this.lblFilePath.Text = "파일 경로: (없음)";
// txtContent
this.txtContent.Location = new System.Drawing.Point(20, 60);
this.txtContent.Multiline = true;
this.txtContent.Name = "txtContent";
this.txtContent.ScrollBars = ScrollBars.Vertical;
this.txtContent.Size = new System.Drawing.Size(400, 200);
this.txtContent.TabIndex = 1;
// btnOpenFile
this.btnOpenFile.Location = new System.Drawing.Point(20, 280);
this.btnOpenFile.Name = "btnOpenFile";
this.btnOpenFile.Size = new System.Drawing.Size(150, 30);
this.btnOpenFile.TabIndex = 2;
this.btnOpenFile.Text = "파일 열기";
this.btnOpenFile.UseVisualStyleBackColor = true;
this.btnOpenFile.Click += new System.EventHandler(this.BtnOpenFile_Click);
// btnSaveFile
this.btnSaveFile.Location = new System.Drawing.Point(200, 280);
this.btnSaveFile.Name = "btnSaveFile";
this.btnSaveFile.Size = new System.Drawing.Size(150, 30);
this.btnSaveFile.TabIndex = 3;
this.btnSaveFile.Text = "파일 저장";
this.btnSaveFile.UseVisualStyleBackColor = true;
this.btnSaveFile.Click += new System.EventHandler(this.BtnSaveFile_Click);
// Form1
this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
this.AutoScaleMode = System.Windows.Forms.AutoScaleMode.Font;
this.ClientSize = new System.Drawing.Size(450, 350);
this.Controls.Add(this.btnSaveFile);
this.Controls.Add(this.btnOpenFile);
this.Controls.Add(this.txtContent);
this.Controls.Add(this.lblFilePath);
this.Name = "Form1";
this.Text = "OpenFileDialog와 SaveFileDialog";
this.ResumeLayout(false);
this.PerformLayout();
}
}
}
5. 실행 결과
- 파일 열기
- "파일 열기" 버튼 클릭 → OpenFileDialog로 텍스트 파일 선택.
- 선택된 파일의 경로가 Label에 표시되고, 파일 내용이 TextBox에 로드됩니다.
- 파일 저장
- TextBox에 텍스트를 입력 → "파일 저장" 버튼 클릭 → SaveFileDialog로 저장 경로와 이름 지정.
- 텍스트 내용이 선택한 파일로 저장되고, Label에 저장 경로가 표시됩니다.
6. 주요 개념 요약
- OpenFileDialog: 파일 열기 대화 상자로 사용자가 파일을 선택할 수 있도록 함.
- SaveFileDialog: 파일 저장 대화 상자로 사용자가 파일을 저장할 경로와 이름을 지정.
- File.ReadAllText/File.WriteAllText: 파일에서 텍스트를 읽고 쓰는 간단한 메서드.
728x90
'Study > C#' 카테고리의 다른 글
C# Windows Forms 강의 31편: ContextMenuStrip으로 동적 컨텍스트 메뉴 구현 (0) | 2025.03.06 |
---|---|
C# Windows Forms 강의 30편: DataGridView 컨트롤로 데이터 관리 (0) | 2025.03.05 |
C# Windows Forms 강의 28편: Timer 컨트롤로 반복 작업 처리 (0) | 2025.03.03 |
C# Windows Forms 강의 27편: Chart 컨트롤을 사용한 데이터 시각화 (0) | 2025.03.02 |
C# Windows Forms 강의 26편: BackgroundWorker로 비동기 작업 처리 (0) | 2025.03.01 |