[.NET 6.0]openFileDialog로 파일 선택 및 리스트에 담기
2023. 9. 25. 11:52ㆍJust do IT/C#
반응형
애플리케이션에서 파일을 선택하고, 리스트에 담아야 하는 경우가 있습니다.
위와 같은 경우, 우측의 + 버튼을 누르면 리스트에 선택된 파일을 담아야 합니다.
이때 openFileDialog를 사용하면 윈도우의 탐색기 기능을 사용하여 파일 선택하고 선택된 파일을 리스트에 담을 수 있습니다.
코드는 아래와 같습니다.
public void FolderOpen()
{
string targetFolderPath = Environment.GetFolderPath(Environment.SpecialFolder.Desktop); //바탕화면을 지정 //현재 디렉토리는 Environment.CurrentDirectory;
string targetName = string.Empty;
string targetPath = string.Empty;
var fileContent = string.Empty;
using (OpenFileDialog openFileDialog = new OpenFileDialog())
{
openFileDialog.InitialDirectory = targetFolderPath;
openFileDialog.Filter = "exe files(*.exe)|*.exe"; //txt files(*.txt)|*.txt|exe files(*.exe)|*.exe|All files (*.*)|*.*
openFileDialog.FilterIndex = 1; // Filter에 지정한 순서대로 노출
openFileDialog.RestoreDirectory = true;
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
//targetName = openFileDialog.SafeFileName; //Get file name only
targetName = openFileDialog.SafeFileName.Substring(0, openFileDialog.SafeFileName.Length - 4); //확장자를 제외한 파일명
targetPath = openFileDialog.FileName; //Get the path of specified file and file name
//Read the contents of the file into a stream
var fileStream = openFileDialog.OpenFile();
using (StreamReader reader = new StreamReader(fileStream))
{
fileContent = reader.ReadToEnd();
}
}
}
ListViewItem item = new ListViewItem(new string[] { targetName, targetPath });
MainForm.mainForm.listView1.Items.Add(item);
// Save the items to application settings
Properties.Settings.Default.ListViewItems.Add($"{targetName},{targetPath}");
Properties.Settings.Default.Save();
// Save the items to application settings
} //FolderOpen
openFileDialog.InitialDirectory = targetFolderPath; - 바탕화면이 열리도록 설정
openFileDialog.Filter = "exe files(*.exe)|*.exe"; - .exe 파일만 필터링 되도록 설정
선택한 파일을 listview에 담고, Properties.Settings에 저장하는 부분까지입니다.
반응형
'Just do IT > C#' 카테고리의 다른 글
[.NET 6.0]RegistryKey를 이용하여 등록되어 있는 시작 프로그램 해제하기 (0) | 2023.09.25 |
---|---|
[.NET 6.0]RegistryKey로 시작 프로그램 등록하기 (0) | 2023.09.25 |
[.NET 6.0]Class 참조하기 (0) | 2023.09.25 |
[.NET 6.0]Windows Form 시작 위치 설정 및 Form Drag&Drop (0) | 2023.09.20 |
[.NET 6.0]Windows Form 스타일 변경하기 (0) | 2023.09.20 |