728x90
반응형

 파일 이름 변경(Rename) 기능 추가하기

이전 글에서는 폴더를 선택할 수 있는 기능을 추가했습니다.
이번에는 파일 이름을 변경(Rename)할 수 있는 기능을 추가해보겠습니다!

파일 이름 변경 기능까지 추가하면 파일 관리 앱으로서 거의 기본 기능을 모두 갖추게 됩니다.


1. 추가 목표

  • 선택한 파일 이름 변경하기
  • 새 파일명을 입력받고, 이름 변경 처리

2. UI 수정 사항

  • TextBox 추가 (Name: txtNewFileName, Placeholder: "새 파일명 입력")
  • Button 추가
    • Button (Name: btnRenameFile, Text: "이름 변경")

3. 코드 추가하기

 파일 이름 변경 버튼 클릭 이벤트

private void btnRenameFile_Click(object sender, EventArgs e)
{
    string folderPath = txtFolderPath.Text;
    string selectedFile = listBoxFiles.SelectedItem as string;
    string newFileName = txtNewFileName.Text.Trim();

    if (string.IsNullOrEmpty(selectedFile))
    {
        MessageBox.Show("변경할 파일을 선택하세요.");
        return;
    }

    if (string.IsNullOrEmpty(newFileName))
    {
        MessageBox.Show("새 파일명을 입력하세요.");
        return;
    }

    string sourcePath = Path.Combine(folderPath, Path.GetFileName(selectedFile));
    string destPath = Path.Combine(folderPath, newFileName);

    try
    {
        if (File.Exists(destPath))
        {
            MessageBox.Show("같은 이름의 파일이 이미 존재합니다.");
            return;
        }

        File.Move(sourcePath, destPath);
        MessageBox.Show("파일 이름 변경 완료!");
        btnLoadFiles.PerformClick();
    }
    catch (Exception ex)
    {
        MessageBox.Show("이름 변경 실패: " + ex.Message);
    }
}

 주의사항

  • 새 파일 이름에 확장자(.txt, .jpg 등)가 필요한 경우 사용자가 직접 포함해야 합니다.
  • 동일 이름 파일이 있을 경우 덮어쓰기 방지를 위해 체크합니다.

4. 주요 포인트 정리

항목 설명

새 이름 입력 TextBox로 새 파일명 입력
이름 변경 File.Move 사용
중복 파일명 체크 File.Exists로 미리 검사

이번 글에서는 WinForms 파일 관리 앱에 파일 이름 변경(Rename) 기능을 추가했습니다.

  • 선택한 파일의 이름을 원하는 이름으로 쉽게 변경할 수 있음
  • 중복 파일명 방지 처리 포함

파일 목록 불러오기 ➔ 검색 ➔ 복사 ➔ 이동 ➔ 삭제 ➔ 이름 변경까지 이제 파일 관리의 거의 모든 기본 기능을 갖추게 되었습니다!

 

728x90
반응형

+ Recent posts