TIP
[C#/Winform] 폴더 및 파일 선택 - CommonOpenFileDialog, OpenFileDialog, FolderBrowserDialog
DoongDev
2020. 7. 22. 13:39
반응형
유튜브 영상을 다운받고 이미지로 변환시켜주는 프로그램을 만들면서 경로를 설정하고 동영상 파일을 선택해야 하는 기능도 추가해야 하는 일이 있었다. 내가 찾아본 바로는 'OpenFileDialog', 'FolderBrowserDialog', 'CommonOpenFileDialog' 총 세가지 방법이 있다.
OpenFileDialog
private void button1_Click(object sender, EventArgs e)
{
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();
}
}
}
}
이 방법은 파일은 선택할 수 있지만 폴더는 선택할 수 없다.
FolderBrowserDialog
private void button1_Click(object sender, EventArgs e)
{
FolderBrowserDialog folderBrowserDialog = new FolderBrowserDialog();
if (folderBrowserDialog.ShowDialog() == DialogResult.OK)
{
MessageBox.Show(folderBrowserDialog.SelectedPath);
}
}
이 방법은 폴더를 선택할 수 있지만 UI가 Tree 구조로 보여지기 때문에 폴더 선택하는데 불편함이 있다.
CommonOpenFileDialog
이 방법은 Property에 true 혹은 false 값을 넣어서 폴더 선택 및 파일 선택을 할 수 있게 설정할 수 있다.
설치 방법
NuGet 패키지 관리
WindowsAPICodePack 검색 후 설치
사용방법
private void findVideoLocationButton_Click(object sender, EventArgs e)
{
CommonOpenFileDialog dialog = new CommonOpenFileDialog();
dialog.IsFolderPicker = true; // true : 폴더 선택 / false : 파일 선택
if (dialog.ShowDialog() == CommonFileDialogResult.Ok)
{
storageLocationTextBox.Text = dialog.FileName;
}
}
위와 같이 활용할 수 있다. 이때 'IsFolderPicker' 값을 true로 설정하면 폴더 선택, false로 설정하면 파일 선택을 할 수 있다.
반응형