728x90
반응형

다중 파일 복사/이동 기능 추가하기

이전 글에서는 파일 하나를 복사하거나 이동하는 기능과 진행률 표시를 구현했습니다.
이번에는 다중 파일을 한 번에 선택해서 복사/이동할 수 있도록 기능을 확장해보겠습니다!

이를 통해 더욱 실용적이고 강력한 파일 관리 앱을 만들어봅니다.


1. 추가 목표

  • ListBox에서 여러 파일 선택 가능하게 변경
  • 선택한 여러 파일을 일괄 복사 또는 이동
  • 복사/이동 진행률 표시

2. UI 수정 사항

  • ListBox (listBoxFiles) 속성 변경
    • SelectionMode ➔ MultiExtended (여러 파일 선택 가능)
  • Button 추가
    • Button (Name: btnBatchCopy, Text: "선택 파일 복사")
    • Button (Name: btnBatchMove, Text: "선택 파일 이동")
  • 기존 ProgressBar(progressBar) 재사용

3. 코드 추가하기

 여러 파일 복사하기

private async void btnBatchCopy_Click(object sender, EventArgs e)
{
    string folderPath = txtFolderPath.Text;
    var selectedFiles = listBoxFiles.SelectedItems;

    if (selectedFiles.Count == 0)
    {
        MessageBox.Show("복사할 파일을 선택하세요.");
        return;
    }

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

    int fileCount = selectedFiles.Count;
    int currentIndex = 0;

    foreach (string filePath in selectedFiles)
    {
        string fileName = Path.GetFileName(filePath);
        string destPath = Path.Combine(folderPath, "복사본_" + fileName);

        await CopyFileAsync(filePath, destPath);

        currentIndex++;
        progressBar.Value = (currentIndex * 100) / fileCount;
    }

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

private async Task CopyFileAsync(string sourcePath, string destPath)
{
    using (FileStream sourceStream = File.Open(sourcePath, FileMode.Open))
    using (FileStream destStream = File.Create(destPath))
    {
        await sourceStream.CopyToAsync(destStream);
    }
}

 여러 파일 이동하기

private async void btnBatchMove_Click(object sender, EventArgs e)
{
    string folderPath = txtFolderPath.Text;
    var selectedFiles = listBoxFiles.SelectedItems;

    if (selectedFiles.Count == 0)
    {
        MessageBox.Show("이동할 파일을 선택하세요.");
        return;
    }

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

    int fileCount = selectedFiles.Count;
    int currentIndex = 0;

    foreach (string filePath in selectedFiles)
    {
        string fileName = Path.GetFileName(filePath);
        string destPath = Path.Combine(folderPath, "이동됨_" + fileName);

        await CopyFileAsync(filePath, destPath);
        File.Delete(filePath);

        currentIndex++;
        progressBar.Value = (currentIndex * 100) / fileCount;
    }

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

4. 주요 포인트 정리

항목 설명

다중 선택 ListBox SelectionMode = MultiExtended 설정
복사 반복 foreach 문으로 선택 파일 반복
진행률 표시 전체 파일 개수 기준으로 현재 진행률 계산
이동 구현 복사 후 원본 파일 삭제

 

이번 글에서는 다중 파일 선택 후 복사/이동 기능을 추가하고,
일괄 진행 상황을 ProgressBar로 표시하는 방법까지 정리했습니다.

이제 이 파일 관리 앱은 꽤 실용적이고 완성도 높은 형태가 되었어요!

 

728x90
반응형

+ Recent posts