C#
[C#] OpenFileDialog로 다중 파일 선택, Default Path 지정
HyoSeong
2021. 2. 18. 00:26
반응형
결론부터 알려드리겠습니다.
public string[] SelectMultiFiles(string defaultPath)
{
string[] selectPath = null;
var openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
if (Directory.Exists(defaultPath))
{
openFileDialog.InitialDirectory = defaultPath;
}
else
{
openFileDialog.InitialDirectory = @"C:\";
}
bool? result = openFileDialog.ShowDialog();
if (result.HasValue && result.Value)
{
selectPath = openFileDialog.FileNames;
}
return selectPath;
}
안녕하세요.
오늘은 파일이나 폴더를 선택할 수 있는 OpenFileDialog에 대해 알아보도록 하겠습니다.
win32 vs forms
OpenFileDialog는 Microsoft.Win32, System.Windows.Forms 두 군데에 구현되어있습니다.
내부적으로 구현 내용은 아래와 같습니다.
사용 방법은 동일하고 약간의 차이점을 아래에 정리해 보았습니다.
이때 using이 사용 가능한 이유는 Forms가 내부적으로 IDisposable을 구현하고 있기 때문입니다.
Forms | win32 | |
using 사용 가능 | O | X |
ShowDialog result type | bool | bool? |
WPF 프로젝트에서 사용할 경우 win32, WinForm 프로젝트에서 사용할 경우 Forms 사용을 추천드립니다.
이번 강의에서는 win32를 사용하여 구현해 보도록 하겠습니다.
OpenFileDialog
public string SelectFile(string defaultPath)
{
string selectPath = string.Empty;
var openFileDialog = new OpenFileDialog();
if (Directory.Exists(defaultPath))
{
openFileDialog.InitialDirectory = defaultPath;
}
else
{
openFileDialog.InitialDirectory = @"C:\";
}
bool? result = openFileDialog.ShowDialog();
if (result.HasValue && result.Value)
{
selectPath = openFileDialog.FileName;
}
return selectPath;
}
public string[] SelectMultiFiles(string defaultPath)
{
string[] selectPath = null;
var openFileDialog = new OpenFileDialog();
openFileDialog.Multiselect = true;
if (Directory.Exists(defaultPath))
{
openFileDialog.InitialDirectory = defaultPath;
}
else
{
openFileDialog.InitialDirectory = @"C:\";
}
bool? result = openFileDialog.ShowDialog();
if (result.HasValue && result.Value)
{
selectPath = openFileDialog.FileNames;
}
return selectPath;
}
감사합니다.
반응형