C#

[C#]OpenFileDialog 활용하기

데브프로그라 2024. 9. 12. 00:13
반응형

C#을 사용하여 파일을 선택하거나 불러오는 기능을 구현하기.
OpenFileDialog의 기본 사용법과 주요 기능에 대해 알아보겠습니다.

// 파일 대화 상자 객체 생성
OpenFileDialog openFileDialog = new OpenFileDialog();
    
// 파일 확장자 지정, png 이미지 파일만 선택하도록 설정
openFileDialog.Filter = "이미지 파일|*.png";
 
//FilterIndex - 대화상자에서 기본으로 선택될 파일 유형의 인덱스 설정
openFileDialog.FilterIndex = 1;

//InitialDirectory - 처음 표시될 디렉토리를 설정.
openFileDialog.InitialDirectory = "*.*";

//RestoreDirectory : 대화상자를 닫을 때 원래의 디렉토리로 복귀할 지 여부를 설정
openFileDialog.RestoreDirectory = true;

// 사용자가 파일을 선택 할 경우
if (openFileDialog.ShowDialog() == DialogResult.OK)
{
  // 선택된 파일의 경로와 이름 저장
  string filePath = openFileDialog.FileName;
  // 선택한 파일 경로 출력
   MessageBox.Show("Selected file: " + filePath);
}


반응형

/* 코드복사 버튼 */ pre { position: relative; overflow: visible; } pre .copy-button { opacity: 0; position: absolute; right: 8px; top: 4px; padding: 6px 18px; color: rgb(255, 255, 255); background: rgba(255, 223, 0, 0.6); border-radius: 5px; transition: opacity .3s ease-in-out; } pre:hover .copy-button { opacity: 1; } pre .copy-button:hover { color: #eee; transition: all ease-in-out 0.3s; } pre .copy-button:active { color: #33f; transition: all ease-in-out 0.1s; } .copy-message:before { content: attr(copy-message); position: absolute; left: -95px; top: 0px; padding: 6px 18px; color: #fff; background: rgba(255, 223, 0, 0.6); border-radius: 5px; } /* 코드복사 버튼 END */