Study/C#

C# Windows Forms 강의 17편: 파일 입출력(File I/O)과 OpenFileDialog, SaveFileDialog

wawManager 2025. 2. 20. 12:00
728x90

1. 강의 개요

이번 강의에서는 Windows Forms에서 **파일 입출력(File I/O)**과 OpenFileDialog, SaveFileDialog를 사용하여 파일을 열고 저장하는 기능을 구현합니다.
파일 입출력은 텍스트 파일 읽기/쓰기 및 데이터를 파일로 저장하거나 불러오는 작업에 필수적입니다.


2. 학습 목표

  1. 파일 입출력을 수행하는 StreamReader와 StreamWriter 사용법 학습.
  2. OpenFileDialog를 사용해 파일 열기 기능 구현.
  3. SaveFileDialog를 사용해 텍스트 파일 저장 기능 구현.

3. OpenFileDialog와 SaveFileDialog

OpenFileDialog

OpenFileDialog는 사용자가 파일을 선택할 수 있는 파일 열기 대화 상자를 제공합니다.

  • 선택한 파일의 경로와 이름을 가져올 수 있습니다.

SaveFileDialog

SaveFileDialog는 사용자가 파일을 저장할 경로와 이름을 선택할 수 있는 대화 상자를 제공합니다.

  • 저장 파일의 경로와 이름을 반환합니다.

주요 속성 및 메서드

속성/메서드 설명 예제

Filter 파일 필터 설정 (예: *.txt, *.csv) `openFileDialog1.Filter = "텍스트 파일
FileName 선택된 파일 이름 string fileName = openFileDialog1.FileName;
ShowDialog() 대화 상자를 열고 결과 반환 (OK or Cancel) if (openFileDialog1.ShowDialog() == DialogResult.OK)

4. 파일 입출력 (File I/O)

StreamReaderStreamWriter

파일 입출력은 StreamReader와 StreamWriter 클래스를 사용해 파일에서 데이터를 읽거나 쓸 수 있습니다.

클래스 설명 예제

StreamReader 텍스트 파일 읽기 StreamReader reader = new StreamReader(filePath);
StreamWriter 텍스트 파일 쓰기 StreamWriter writer = new StreamWriter(filePath);

5. 실습: 파일 열기 및 저장 기능 구현

요구사항

  1. OpenFileDialog를 사용해 텍스트 파일의 내용을 TextBox에 불러오기.
  2. SaveFileDialog를 사용해 TextBox 내용을 파일로 저장.
  3. Label로 파일 이름 표시.

폼 구성

컨트롤 타입 이름 텍스트 위치 크기

Label lblFileName "파일 경로: (없음)" (20, 20) (400 x 30)
TextBox textBox1 (없음) (20, 60) (400 x 200)
Button btnOpen "파일 열기" (20, 280) (100 x 30)
Button btnSave "파일 저장" (140, 280) (100 x 30)

코드 작성

Form1.cs

using System;
using System.IO;
using System.Windows.Forms;

namespace WindowsFormsApp1
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
            InitializeFileIO();
        }

        private void InitializeFileIO()
        {
            // "파일 열기" 버튼 클릭 이벤트
            btnOpen.Click += (sender, e) =>
            {
                using (OpenFileDialog openFileDialog = new OpenFileDialog())
                {
                    openFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
                    openFileDialog.Title = "파일 열기";

                    if (openFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        lblFileName.Text = $"파일 경로: {openFileDialog.FileName}";
                        textBox1.Text = File.ReadAllText(openFileDialog.FileName);
                    }
                }
            };

            // "파일 저장" 버튼 클릭 이벤트
            btnSave.Click += (sender, e) =>
            {
                using (SaveFileDialog saveFileDialog = new SaveFileDialog())
                {
                    saveFileDialog.Filter = "텍스트 파일 (*.txt)|*.txt|모든 파일 (*.*)|*.*";
                    saveFileDialog.Title = "파일 저장";

                    if (saveFileDialog.ShowDialog() == DialogResult.OK)
                    {
                        File.WriteAllText(saveFileDialog.FileName, textBox1.Text);
                        lblFileName.Text = $"저장된 파일: {saveFileDialog.FileName}";
                        MessageBox.Show("파일이 성공적으로 저장되었습니다.", "파일 저장");
                    }
                }
            };
        }
    }
}

디자이너 코드: Form1.Designer.cs

namespace WindowsFormsApp1
{
    partial class Form1
    {
        private System.ComponentModel.IContainer components = null;
        private Label lblFileName;
        private TextBox textBox1;
        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.lblFileName = new Label();
            this.textBox1 = new TextBox();
            this.btnOpen = new Button();
            this.btnSave = new Button();
            this.SuspendLayout();

            // lblFileName
            this.lblFileName.AutoSize = true;
            this.lblFileName.Location = new System.Drawing.Point(20, 20);
            this.lblFileName.Name = "lblFileName";
            this.lblFileName.Size = new System.Drawing.Size(120, 20);
            this.lblFileName.TabIndex = 0;
            this.lblFileName.Text = "파일 경로: (없음)";

            // textBox1
            this.textBox1.Location = new System.Drawing.Point(20, 60);
            this.textBox1.Multiline = true;
            this.textBox1.Name = "textBox1";
            this.textBox1.ScrollBars = ScrollBars.Vertical;
            this.textBox1.Size = new System.Drawing.Size(400, 200);
            this.textBox1.TabIndex = 1;

            // btnOpen
            this.btnOpen.Location = new System.Drawing.Point(20, 280);
            this.btnOpen.Name = "btnOpen";
            this.btnOpen.Size = new System.Drawing.Size(100, 30);
            this.btnOpen.TabIndex = 2;
            this.btnOpen.Text = "파일 열기";
            this.btnOpen.UseVisualStyleBackColor = true;

            // btnSave
            this.btnSave.Location = new System.Drawing.Point(140, 280);
            this.btnSave.Name = "btnSave";
            this.btnSave.Size = new System.Drawing.Size(100, 30);
            this.btnSave.TabIndex = 3;
            this.btnSave.Text = "파일 저장";
            this.btnSave.UseVisualStyleBackColor = true;

            // Form1
            this.AutoScaleDimensions = new System.Drawing.SizeF(8F, 20F);
            this.AutoScaleMode = AutoScaleMode.Font;
            this.ClientSize = new System.Drawing.Size(450, 350);
            this.Controls.Add(this.btnSave);
            this.Controls.Add(this.btnOpen);
            this.Controls.Add(this.textBox1);
            this.Controls.Add(this.lblFileName);
            this.Name = "Form1";
            this.Text = "파일 입출력 예제";
            this.ResumeLayout(false);
            this.PerformLayout();
        }
    }
}

6. 실행 결과

  1. 파일 열기
    • "파일 열기" 버튼 클릭 → OpenFileDialog로 텍스트 파일 선택 → 파일 내용이 TextBox에 표시되고 Label에 파일 경로 표시.
  2. 파일 저장
    • TextBox에 텍스트를 입력 → "파일 저장" 버튼 클릭 → SaveFileDialog로 파일 저장 위치와 이름 선택 → 입력한 텍스트가 파일로 저장.

7. 주요 개념 요약

  1. OpenFileDialog: 파일 열기 대화 상자로 사용자가 파일을 선택할 수 있도록 함.
  2. SaveFileDialog: 파일 저장 대화 상자로 사용자가 파일을 저장할 위치와 이름을 선택.
  3. StreamReader/StreamWriter: 파일을 읽고 쓰는 데 사용되며, File.ReadAllText와 File.WriteAllText 같은 간편 메서드도 활용 가능.
728x90