.Net 5.0의 WPF에서 WinForm을 이용해 OpenFileDialog를 사용하는 방법에 대해 알아봅니다.

 

 

 

1. 프로젝트 설정.

 

IDE는 VisualStudio 2019 CE를 사용했으며 프로젝트는 .Net 5.0을 사용한 WPF 프로젝트를 생성하였습니다.

 

 

 

2. OpenFileDialog 사용해보기.

 

먼저 적당히 xaml에 버튼을 추가한 후 이벤트를 생성합니다.

 

MSDN의 .Net5.0에 해당하는 OpenFileDialog 클래스를 보면 다음과 같이 사용할 수 있다고 나와있습니다.

 

// public sealed class OpenFileDialog : System.Windows.Forms.FileDialog
var fileContent = string.Empty;
var filePath = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
    openFileDialog.InitialDirectory = "c:\\";
    openFileDialog.Filter = "txt files (*.txt)|*.txt|All files (*.*)|*.*";
    openFileDialog.FilterIndex = 2;
    openFileDialog.RestoreDirectory = true;
    if (openFileDialog.ShowDialog() == DialogResult.OK)
    {
        //Get the path of specified file
        filePath = openFileDialog.FileName;
        //Read the contents of the file into a stream
        var fileStream = openFileDialog.OpenFile();
        using (StreamReader reader = new StreamReader(fileStream))
        {
            fileContent = reader.ReadToEnd();
        }
    }
}
MessageBox.Show(fileContent, "File Content at path: " + filePath, MessageBoxButtons.OK);

 

위와 같이 이벤트를 수정해 봅시다.

 

 

슬프게도 에러가 발생합니다. 심지어 "System.Windows.Forms.FileDialog"도 찾을 수 없습니다. 

 

 

 

. .Net 5.0 WPF 프로젝트에서 WinForm 사용하기.

 

사실 .Net5.0 WPF 프로젝트에서 WinForm은 사용할 수 없는 게 기본값입니다. WinForm을 사용하기 위해선 프로젝트 설정으로 가서 수동으로 WinForm을 사용하도록 설정해야 합니다.

 

프로젝트 파일을 열어 설정을 확인합니다.

 

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<OutputType>WinExe</OutputType>
		<TargetFramework>net5.0-windows</TargetFramework>
		<UseWPF>true</UseWPF>
	</PropertyGroup>
</Project>

 

별다른 설정을 하지 않았다면 위와 같은 설정을 확인할 수 있습니다. 이제 여기 "PropertyGroup"에 "UseWindowsForms" 항목을 추가해 줍니다.

 

<Project Sdk="Microsoft.NET.Sdk">
	<PropertyGroup>
		<OutputType>WinExe</OutputType>
		<TargetFramework>net5.0-windows</TargetFramework>
		<UseWPF>true</UseWPF>
		<UseWindowsForms>true</UseWindowsForms>
	</PropertyGroup>
</Project>

 

이제 다시 코드로 돌아가 봅시다.

 

 

이제 정상적으로 WinForm을 사용할 수 있습니다.

 

 

 

 

 

반응형

+ Recent posts