728x90
반응형

이동 기능과 진행률 표시 추가하기

이전 글에서는 파일 목록 불러오기, 복사, 삭제 기능을 가진 기본 파일 관리 앱을 만들었습니다.
이번에는 기능을 더 확장해서 파일 이동(Move) 기능을 추가하고, 복사/이동 시 진행률(ProgressBar) 도 표시해보겠습니다!


1. 추가 목표

  • 파일 이동(Move) 기능 구현
  • 복사/이동할 때 진행 상황을 ProgressBar로 표시

2. UI 요소 추가

  • ProgressBar (Name: progressBar) - 초기 Visible: false, Minimum: 0, Maximum: 100
  • Button (Name: btnMoveFile, Text: "이동") 추가

3. 코드 수정 및 추가

 이동 기능 추가

private async void btnMoveFile_Click(object sender, EventArgs e)
{
    string folderPath = txtFolderPath.Text;
    string fileName = txtFileName.Text;

    string sourcePath = Path.Combine(folderPath, fileName);
    string destPath = Path.Combine(folderPath, "이동됨_" + fileName);

    if (!File.Exists(sourcePath))
    {
        MessageBox.Show("파일이 존재하지 않습니다.");
        return;
    }

    progressBar.Visible = true;
    progressBar.Value = 0;

    await MoveFileWithProgressAsync(sourcePath, destPath);

    MessageBox.Show("파일 이동 완료!");
    progressBar.Visible = false;
    btnLoadFiles.PerformClick();
}

private async Task MoveFileWithProgressAsync(string sourcePath, string destPath)
{
    const int bufferSize = 81920; // 80KB 버퍼 크기
    byte[] buffer = new byte[bufferSize];

    FileInfo fileInfo = new FileInfo(sourcePath);
    long totalBytes = fileInfo.Length;
    long readBytes = 0;

    using (FileStream sourceStream = new FileStream(sourcePath, FileMode.Open, FileAccess.Read))
    using (FileStream destStream = new FileStream(destPath, FileMode.Create, FileAccess.Write))
    {
        int bytesRead;
        while ((bytesRead = await sourceStream.ReadAsync(buffer, 0, buffer.Length)) > 0)
        {
            await destStream.WriteAsync(buffer, 0, bytesRead);
            readBytes += bytesRead;

            int progress = (int)((readBytes * 100) / totalBytes);
            progressBar.Value = Math.Min(progress, 100);
        }
    }

    File.Delete(sourcePath); // 복사 완료 후 원본 삭제
}

4. 주요 포인트 정리

항목 설명

파일 이동 구현 직접 복사한 후 원본 삭제 방식으로 구현
진행률 표시 복사 진행 중 읽은 바이트 수로 퍼센트 계산
ProgressBar 제어 Visible 속성으로 시작/완료 시 표시/숨김
await 활용 UI 멈춤 없이 부드럽게 동작

5. 전체 흐름 요약

  1. 사용자가 파일 선택 → 이동 버튼 클릭
  2. ProgressBar를 보여주며 파일을 복사
  3. 복사가 끝나면 원본 파일 삭제 (실제 이동 효과)
  4. 이동 완료 메시지 + 파일 목록 새로고침

이번 글에서는

  • 파일 이동 기능 추가
  • 복사/이동 시 진행률 표시(ProgressBar) 를 통해 파일 관리 앱을 더욱 실용적으로 확장했습니다.

비동기 작업 + 사용자 경험 개선(UI 피드백) 을 동시에 연습해볼 수 있었습니다!

 

728x90
반응형

+ Recent posts