[C# WPF] 파일 열기로 파일 불러오기

이슬기·2024년 7월 3일
0

C#

목록 보기
4/5

C# WPF에서 Microsoft.Win32 namespace의 OpenFileDialog class를 활용하여 파일 불러오기를 구현하였습니다.

저는 UserControlViewModel을 연결해서 사용하였습니다.

1) 컨트롤러.xaml

TextBox와 Button을 포함하는 간단한 UI를 정의합니다. TextBox는 파일명을 표시하며, Button은 파일 열기 대화상자를 엽니다.

<UserControl x:Class="[컨트롤러 경로]"
             xmlns="http://schemas.microsoft.com/winfx/2006/xaml/presentation"
             xmlns:x="http://schemas.microsoft.com/winfx/2006/xaml"
             Title="MainWindow" Height="200" Width="300">
    <StackPanel Orientation="Horizontal">
		<TextBox Text="{Binding SelectedBackupFile, Mode=TwoWay, UpdateSourceTrigger=PropertyChanged}"
         		Width="200" Height="30" Margin="0 5 15 0" IsReadOnly="True"/>
		<Button Command="{Binding OpenFileCommand}"
        		Content="Open File"/>
    </StackPanel>
</UserControl>

2) 컨트롤러.xaml.cs

Control 클래스의 생성자에서 DataContextViewModel로 설정하여 ViewViewModel을 연결합니다.

using System.Windows.Controls;

namespace [컨트롤러 경로]
{
    public partial class [~Control] : UserControl
    {
        public [~Control]()
        {
            InitializeComponent();
            DataContext = new [~Control]ViewModel();
        }
    }
}

3) 컨트롤러ViewModel.cs

  • INotifyPropertyChanged 인터페이스를 구현하여 데이터 바인딩을 지원합니다.
  • OpenFileCommandRelayCommand로 초기화하고, OpenFile 메서드를 실행합니다.
  • OpenFile 메서드는 OpenFileDialog를 열고 파일을 선택하면, 선택한 파일의 이름을 SelectedBackupFile 속성에 설정합니다.
using Microsoft.Win32;
using System.ComponentModel;
using System.IO;
using System.Windows.Input;

namespace [뷰모델 경로]
{
    public partial class [컨트롤러뷰모델 명] : INotifyPropertyChanged
    {
        private string _selectedBackupFile;

        public ICommand OpenFileCommand { get; set; }

        public InfoControlViewModel()
        {
            OpenFileCommand = new RelayCommand(OpenFile);
        }

        public string SelectedBackupFile
        {
            get => _selectedBackupFile;
            set
            {
                _selectedBackupFile = value;
                OnPropertyChanged(nameof(SelectedBackupFile));
            }
        }

        private void OpenFile()
        {
            // file dialog box를 열 경로 구성
            var dialog = new OpenFileDialog();
            // MyDocuments 폴더 경로 가져오기
            string backupDirectory = System.Environment.GetFolderPath(Environment.SpecialFolder.MyDocuments);
            // "backup" 폴더 경로 설정
            string backupFolderPath = Path.Combine(backupDirectory, "backup");
            
            // 초기 경로 및 파일 필터 설정
            dialog.InitialDirectory = backupFolderPath;
            dialog.DefaultExt = ".db";
            dialog.Filter = "Data Base File(.db)|*.db";

            // 파일 선택 대화상자 열기
            bool? result = dialog.ShowDialog();

            if (result == true)
            {
                // 파일 이름을 SelectedBackupFile 속성에 설정
                SelectedBackupFile = Path.GetFileName(dialog.FileName);
            }
        }
        
        // INotifyPropertyChanged 인터페이스 구현
        public event PropertyChangedEventHandler PropertyChanged;

        protected void OnPropertyChanged(string propertyName)
        {
            PropertyChanged?.Invoke(this, new PropertyChangedEventArgs(propertyName));
        }

4) RelayCommand.cs

ICommand 인터페이스를 구현하여 명령을 정의합니다. RelayCommand명령 실행조건을 간단히 정의할 수 있도록 도와줍니다.

ICommandRelayCommand에 대해서는 추후에 다룰 예정입니다.

using System;
using System.Windows.Input;

namespace [네임스페이스명]
{
    public class RelayCommand : ICommand
    {
        private readonly Action _execute;
        private readonly Func<bool> _canExecute;

        public RelayCommand(Action execute, Func<bool> canExecute = null)
        {
            _execute = execute;
            _canExecute = canExecute;
        }

        public event EventHandler CanExecuteChanged;

        public bool CanExecute(object parameter)
        {
            return _canExecute == null || _canExecute();
        }

        public void Execute(object parameter)
        {
            _execute();
        }

        public void RaiseCanExecuteChanged()
        {
            CanExecuteChanged?.Invoke(this, EventArgs.Empty);
        }
    }
}

  • 버튼 디자인은 별도로 설정한 사진입니다..!

    파일 선택 버튼을 클릭하면

OpenFileDialog가 보이게 되고

파일 하나를 선택하여 열면 파일 이름이 TextBox에 보이게 됩니다.

참고
1)
https://learn.microsoft.com/ko-kr/dotnet/desktop/wpf/windows/how-to-open-common-system-dialog-box?view=netdesktop-8.0
2)
https://rhkdrmfh.tistory.com/119

0개의 댓글