1 / 23

19장 파일 작업하기

19장 파일 작업하기. 이번 강의에서 배울 내용. 파일 열기 대화상자와 파일 저장 대화상자 컨트롤 사용하기 System.IO.File 로 파일 조작하기 System.IO.Directory 로 디렉토리 조작하기. 파일 열기 대화상자와 파일 저장 대화상자 컨트롤 사용하기. Manipulating Files 라는 제목의 새로운 Windows 응용 프로그램 만들기

Download Presentation

19장 파일 작업하기

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. 19장 파일 작업하기

  2. 이번 강의에서 배울 내용 • 파일 열기 대화상자와 파일 저장 대화상자 컨트롤 사용하기 • System.IO.File로 파일 조작하기 • System.IO.Directory로 디렉토리 조작하기

  3. 파일 열기 대화상자와 파일 저장 대화상자 컨트롤 사용하기 • Manipulating Files라는 제목의 새로운 Windows 응용 프로그램 만들기 • 솔루션 탐색기에서 Form1.cs 이름을 frmManipulatingFiles.cs로 바꾸고, 폼의 Text 속성에 Manipulating Files라고 입력한다. • 폼에 새로운 텍스트 상자를 추가하고 그 속성을 다음과 같이 설정

  4. 파일 열기 대화상자 사용하기 • 도구 모음에서 OpenFileDialog 항목을 더블클릭하여 프로젝트에 새로운 Open File Dialog 컨트롤 추가 • Open File Dialog 컨트롤 • 사용자가 파일을 검색하고 선택할 수 있도록 대화상자를 화면에 표시하고자 할 때 사용 Open File Dialog 컨트롤 폼에 Open File Dialog 컨트롤 추가

  5. 폼에 버튼을 추가하고, 그 속성을 다음과 같이 설정 • 도구상자에서 버튼을 더블클릭하고, Click 이벤트에 다음 코드 추가 openFileDialog1.InitialDirectory = @"C:\"; openFileDialog1.Title = "파일 선택"; openFileDialog1.FileName = "";

  6. 파일 형식 지정하기 • Filter 속성 : 어떤 종류의 파일을 표시할 것인지를 결정 • 기본 형식 설명|*.확장자 • 예제 control.Filter = "Windows Bitmaps (*.bmp)|*.bmp"; control.Filter = "Windows Bitmaps (*.bmp)|*.bmp|JPEG Files (*.jpg)|*.jpg"; • 예제 프로시저에 다음 문장 입력 openFileDialog1.Filter = "Text Files (*.txt)|*.txt"; openFileDialog1.FilterIndex = 1;

  7. 파일 열기 대화상자 표시하기 • 선택한 파일 이름을 txtSource 텍스트 상자에 보여주기 위해, 프로시저에 다음 문장 입력 if (openFileDialog1.ShowDialog() != DialogResult.Cancel) txtSource.Text = openFileDialog1.FileName; else txtSource.Text = "";

  8. 파일 저장 대화상자 컨트롤 사용하기 • 폼에 새로운 텍스트 상자를 추가하고 속성을 다음과 같이 설정 • 저장하고자 하는 파일 이름을 지정할 수 있도록, 폼에 새로운 버튼을 추가하고, 속성을 다음과 같이 설정 • 도구 모음에서 SaveFileDialog 항목을 더블클릭하여 프로젝트에 컨트롤 추가 • btnSaveFile 버튼의 Click 이벤트에 다음 코드 추가 saveFileDialog1.Title = "대상 파일 지정"; saveFileDialog1.Filter = "Text Files (*.txt)|*.txt"; saveFileDialog1.FilterIndex = 1; saveFileDialog1.OverwritePrompt = true; 텍스트 상자 속성 버튼 속성

  9. 선택된 파일 이름을 txtDestination 텍스트 상자에 보여주기 위해 다음 코드 입력 if (saveFileDialog1.ShowDialog() != DialogResult.Cancel) txtDestination.Text = saveFileDialog1.FileName; • <F5>를 눌러서 프로젝트를 실행하고, 파일 선택

  10. File 객체를 통해 파일 처리하기 • 파일 시스템에서 하고자 하는 거의 모든 일을 위해서는 System.IO의 객체 속성 사용 • 특히, System.IO.File과 System.IO.Directory 객체를 사용하면 파일과 디렉터리(폴더)의 특별한 처리가 가능

  11. 파일이 존재하는지 확인하기 • 복사 또는 삭제 등과 같은 모든 파일 관련 작업을 수행하기 전에는 파일이 존재하는지 확인하는 것이 바람직 함 • 파일이 존재하는지 확인하기 위해 System.IO.File 객체의 Exists() 메서드 사용 • 폼 클래스에 다음 함수를 추가한다. bool SourceFileExists() { if (!System.IO.File.Exists(txtSource.Text)) { MessageBox.Show("원본 파일이 존재하지 않습니다."); return false; } else return true; }

  12. 파일 복사하기 • 파일 복사를 위해서는 System.IO.File 클래스의 Copy() 메서드 사용 • 폼에 버튼을 새로 추가하고 속성을 다음과 같이 설정 • Copy 버튼을 더블클릭하고 다음 코드를 추가한다. if (!SourceFileExists()) return; System.IO.File.Copy(txtSource.Text, txtDestination.Text); MessageBox.Show("파일이 성공적으로 복사되었습니다."); • 파일 복사코드 테스트하기

  13. 파일 이동하기(이름바꾸기) • 파일을 이동시킬 때는 System.IO.File 객체의 Move() 메서드 사용 • 파일이름을 바꿀때에도 System.IO.File의 Move()메서드 사용 • 선택한 파일을 지정한 경로와 파일 이름으로 이동시키는 새로운 버튼을 폼에 추가하고 다음과 같이 속성 설정 • Move 버튼을 더블클릭하고, Click 이벤트에 다음 코드 추가 if (!SourceFileExists()) return; System.IO.File.Move(txtSource.Text, txtDestination.Text); MessageBox.Show("파일이 성공적으로 이동되었습니다.");

  14. 파일 삭제하기 • System.IO.File의 Delete() 메서드를 사용하면 파일이 영구적으로 삭제됨(파일이 휴지통으로 이동하지 않음) • 버튼을 클릭하면 원본 파일을 삭제하도록, 새로운 버튼을 추가하고 다음과 같이 속성 설정 • 버튼을 더블클릭하고 버튼의 Click 이벤트에 다음 코드 추가 if (!SourceFileExists()) return; if (MessageBox.Show("원본 파일을 정말 삭제하시겠습니까?", "삭제 확인",MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes) { System.IO.File.Delete(txtSource.Text); MessageBox.Show("파일이 성공적으로 삭제되었습니다."); }

  15. File 속성 알아내기 • 탐색기에서 파일 속성 보기 • 탐색기를 열고, 아무 파일을 마우스 오른쪽 버튼으로 클릭하고 속성을 선택하여파일의 속성 살펴보기 • 코드를 통해 파일 속성 알아보기 • 일부 속성은 System.IO.File 객체에서 직접 알 수 있으며, 다른 데이터들은 FileAttributes 객체 사용

  16. 파일에 대한 날짜와 시간 정보 알아내기 • System.IO.File 객체는 이들 날짜에 대한 메서드 제공

  17. 파일의 속성 알아내기 • 파일의 속성 알아내기 • System.IO.File의 GetAttributes() 메서드는 FileAttributes 열거형 값을 반환한다.

  18. 파일 속성을 읽어들이는 코드 작성하기 • Picture Viewer 프로젝트에서 화면에 표시되어있는 그림의 파일 속성을 볼 수 있도록 수정 • Toolstrip(도구 모음)에 새로운 도구 버튼을 추가하고, 그 이름을 tbbGetFileAttributes라고 변경 • 버튼의 이미지에 Properties.ico를 지정하고, ToolTipText 속성에 Get File Attributes라고 입력 • 새 버튼을 더블클릭하고 버튼의 Click 이벤트에 다음페이지의 코드 입력

  19. // 파일이 열려 있는지 확인한다. if ((ofdSelectPicture.FileName) == "") { MessageBox.Show("열린 파일이 없습니다."); return; } // 문자열을 연결하기 위해 스트링 빌더(string builder)를 생성한다. System.Text.StringBuilder stbProperties = new System.Text.StringBuilder(""); System.IO.FileAttributes fileAttributes; // 데이터 불러오기 stbProperties.Append("생성: "); stbProperties.Append(System.IO.File.GetCreationTime(ofdSelectPicture. FileName)); stbProperties.Append("\r\n"); stbProperties.Append("액세스: "); stbProperties.Append(System.IO.File.GetLastAccessTime(ofdSelectPicture. FileName)); stbProperties.Append("\r\n"); stbProperties.Append("수정: "); stbProperties.Append(System.IO.File.GetLastWriteTime(ofdSelectPicture. FileName)); // 파일 속성 불러오기 fileAttributes = System.IO.File.GetAttributes(ofdSelectPicture. FileName); stbProperties.Append("\r\n");

  20. // 특정 속성을 추출하기 위해 이진 AND를 사용한다. stbProperties.Append("표준: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Normal) == System.IO.FileAttributes.Normal)); stbProperties.Append("\r\n"); stbProperties.Append("숨김: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Hidden) == System.IO.FileAttributes.Hidden)); stbProperties.Append("\r\n"); stbProperties.Append("읽기전용: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.ReadOnly) == System.IO.FileAttributes.ReadOnly)); stbProperties.Append("\r\n"); stbProperties.Append("시스템: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.System) == System.IO.FileAttributes.System)); stbProperties.Append("\r\n");

  21. stbProperties.Append("임시 파일: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Temporary) == System.IO.FileAttributes.Temporary)); stbProperties.Append("\r\n"); stbProperties.Append("보관: "); stbProperties.Append( Convert.ToBoolean((fileAttributes & System.IO.FileAttributes.Archive) == System.IO.FileAttributes.Archive)); MessageBox.Show(stbProperties.ToString());

  22. 파일속성 예제 실행결과

  23. Directory 객체를 사용하여 디렉토리 조작하기 • 디렉터리 생성 System.IO.Directory.CreateDirectory(@"c:\my new directory"); • 디렉터리가 존재하는지 알아보기 MessageBox.Show(Convert.ToString(System.IO.Directory.Exists (@"c:\temp"))); • 디렉터리 이동시키기 System.IO.Directory.Move(@"c:\current directory name", @"d:\new directory name"); • 디렉터리 삭제하기 System.IO.Directory.Delete(@"c:\temp", true);

More Related