다음을 통해 공유


방법: OpenFileDialog를 사용하여 파일 열기

System.Windows.Forms.OpenFileDialog 구성 요소는 파일을 찾아보고 선택하기 위한 Windows 대화 상자를 엽니다. 선택한 파일을 열고 읽으려면 OpenFileDialog.OpenFile 메서드를 사용하거나 System.IO.StreamReader 클래스의 인스턴스를 만들 수 있습니다. 다음 예제는 두 가지 방법을 모두 보여 줍니다.

.NET Framework에서 FileName 속성을 가져오거나 설정하려면 System.Security.Permissions.FileIOPermission 클래스에서 부여한 권한 수준이 필요합니다. 이 예제에서는 FileIOPermission 권한 검사를 실행하며, 부분 신뢰 컨텍스트에서 실행되는 경우 권한 부족으로 인해 예외를 throw할 수 있습니다. 자세한 내용은 코드 액세스 보안 기본 사항을 참조하세요.

C# 또는 Visual Basic 명령줄에서 이러한 예제를 .NET Framework 앱으로 빌드하고 실행할 수 있습니다. 자세한 내용은 csc.exe를 사용한 명령줄 빌드 또는 명령줄에서 빌드를 참조하세요.

.NET Core 3.0부터 시작하여 .NET Core Windows Forms <폴더 이름>.csproj 프로젝트 파일이 있는 폴더에서 .NET Core Windows 앱으로 예제를 빌드하고 실행할 수도 있습니다.

예: StreamReader를 사용하여 파일을 스트림으로 읽기

다음 예제에서는 Windows Forms Button 컨트롤의 Click 이벤트 처리기를 사용하여 ShowDialog 메서드로 OpenFileDialog를 엽니다. 사용자가 파일을 선택하고 확인을 선택하면 StreamReader 클래스의 인스턴스가 파일을 읽고 양식의 텍스트 상자에 해당 내용을 표시합니다. 파일 스트림에서 읽기에 대한 자세한 내용은 FileStream.BeginReadFileStream.Read를 참조하세요.

using System;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;

public class OpenFileDialogForm : Form
{
    [STAThread]
    public static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new OpenFileDialogForm());
    }

    private Button selectButton;
    private OpenFileDialog openFileDialog1;
    private TextBox textBox1;

    public OpenFileDialogForm()
    {
        openFileDialog1 = new OpenFileDialog();
        selectButton = new Button
        {
            Size = new Size(100, 20),
            Location = new Point(15, 15),
            Text = "Select file"
        };
        selectButton.Click += new EventHandler(SelectButton_Click);
        textBox1 = new TextBox
        {
            Size = new Size(300, 300),
            Location = new Point(15, 40),
            Multiline = true,
            ScrollBars = ScrollBars.Vertical
        };
        ClientSize = new Size(330, 360);
        Controls.Add(selectButton);
        Controls.Add(textBox1);
    }
    private void SetText(string text)
    {
        textBox1.Text = text;
    }
    private void SelectButton_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                var sr = new StreamReader(openFileDialog1.FileName);
                SetText(sr.ReadToEnd());
            }
            catch (SecurityException ex)
            {
                MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
                $"Details:\n\n{ex.StackTrace}");
            }
        }
    }
}
Imports System.Drawing
Imports System.IO
Imports System.Security
Imports System.Windows.Forms

Public Class OpenFileDialogForm : Inherits Form

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(False)
        Application.EnableVisualStyles()
        Dim frm As New OpenFileDialogForm()
        Application.Run(frm)
    End Sub

    Dim WithEvents SelectButton As Button
    Dim openFileDialog1 As OpenFileDialog
    Dim TextBox1 As TextBox

    Private Sub New()
        ClientSize = New Size(400, 400)
        openFileDialog1 = New OpenFileDialog()
        SelectButton = New Button()
        With SelectButton
            .Text = "Select file"
            .Location = New Point(15, 15)
            .Size = New Size(100, 25)
        End With
        TextBox1 = New TextBox()
        With TextBox1
            .Size = New Size(300, 300)
            .Location = New Point(15, 50)
            .Multiline = True
            .ScrollBars = ScrollBars.Vertical
        End With
        Controls.Add(SelectButton)
        Controls.Add(TextBox1)
    End Sub

    Private Sub SetText(text)
        TextBox1.Text = text
    End Sub

    Public Sub SelectButton_Click(sender As Object, e As EventArgs) _
              Handles SelectButton.Click
        If openFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                Dim sr As New StreamReader(openFileDialog1.FileName)
                SetText(sr.ReadToEnd())
            Catch SecEx As SecurityException
                MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
                $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
            End Try
        End If
    End Sub
End Class

예: OpenFile을 사용하여 필터링된 선택 영역에서 파일 열기

다음 예제에서는 Button 컨트롤의 Click 이벤트 처리기를 사용하여 텍스트 파일만 표시하는 필터로 OpenFileDialog를 엽니다. 사용자가 텍스트 파일을 선택하고 확인을 선택하면 OpenFile 메서드가 메모장 파일을 여는 데 사용됩니다.

using System;
using System.ComponentModel;
using System.Diagnostics;
using System.Drawing;
using System.IO;
using System.Security;
using System.Windows.Forms;

public class OpenFileDialogForm : Form
{
    [STAThread]
    public static void Main()
    {
        Application.SetCompatibleTextRenderingDefault(false);
        Application.EnableVisualStyles();
        Application.Run(new OpenFileDialogForm());
    }

    private Button selectButton;
    private OpenFileDialog openFileDialog1;

    public OpenFileDialogForm()
    {
        openFileDialog1 = new OpenFileDialog()
        {
            FileName = "Select a text file",
            Filter = "Text files (*.txt)|*.txt",
            Title = "Open text file"
        };

        selectButton = new Button()
        {
            Size = new Size(100, 20),
            Location = new Point(15, 15),
            Text = "Select file"
        };
        selectButton.Click += new EventHandler(selectButton_Click);
        Controls.Add(selectButton);
    }

    private void selectButton_Click(object sender, EventArgs e)
    {
        if (openFileDialog1.ShowDialog() == DialogResult.OK)
        {
            try
            {
                var filePath = openFileDialog1.FileName;
                using (Stream str = openFileDialog1.OpenFile())
                {
                    Process.Start("notepad.exe", filePath);
                }
            }
            catch (SecurityException ex)
            {
                MessageBox.Show($"Security error.\n\nError message: {ex.Message}\n\n" +
                $"Details:\n\n{ex.StackTrace}");
            }
        }
    }
}
Imports System.ComponentModel
Imports System.Diagnostics
Imports System.IO
Imports System.Security
Imports System.Windows.Forms

Public Class OpenFileDialogForm : Inherits Form
    Dim WithEvents selectButton As Button
    Dim openFileDialog1 As OpenFileDialog

    Public Shared Sub Main()
        Application.SetCompatibleTextRenderingDefault(false)
        Application.EnableVisualStyles()
        Dim frm As New OpenFileDialogForm()
        Application.Run(frm)
    End Sub

    Private Sub New()
        openFileDialog1 = New OpenFileDialog() With
        {
           .FileName = "Select a text file",
           .Filter = "Text files (*.txt)|*.txt",
           .Title = "Open text file"
        }

        selectButton = New Button() With {.Text = "Select file"}
        Controls.Add(selectButton)
    End Sub

    Public Sub selectButton_Click(sender As Object, e As EventArgs) _
            Handles selectButton.Click
        If OpenFileDialog1.ShowDialog() = DialogResult.OK Then
            Try
                Dim filePath = OpenFileDialog1.FileName
                Using str = openFileDialog1.OpenFile()
                    Process.Start("notepad.exe", filePath)
                End Using
            Catch SecEx As SecurityException
                MessageBox.Show($"Security error:{vbCrLf}{vbCrLf}{SecEx.Message}{vbCrLf}{vbCrLf}" &
                $"Details:{vbCrLf}{vbCrLf}{SecEx.StackTrace}")
            End Try
        End If
    End Sub
End Class

참고 항목