본문 바로가기
C#

C#로 특정 폴더 내 파일 이름 변경

by 공부봇 2025. 1. 3.
반응형

아래는 특정 폴더 내 모든 파일을 읽고, .exe 확장자를 가진 파일에서 파일 이름의 cam2라는 단어를 cam1로 바꾸는 C# 코드입니다.

using System;
using System.IO;

class Program
{
    static void Main(string[] args)
    {
        // 특정 폴더 경로 설정
        string folderPath = @"C:\Your\Folder\Path";

        if (!Directory.Exists(folderPath))
        {
            Console.WriteLine("지정된 폴더가 존재하지 않습니다.");
            return;
        }

        // 폴더 내 모든 파일 검색
        string[] files = Directory.GetFiles(folderPath, "*.exe");

        foreach (var filePath in files)
        {
            string fileName = Path.GetFileName(filePath); // 파일 이름만 추출
            string directory = Path.GetDirectoryName(filePath); // 디렉토리 경로 추출

            if (fileName.Contains("cam2"))
            {
                // 파일 이름에서 cam2를 cam1로 변경
                string newFileName = fileName.Replace("cam2", "cam1");
                string newFilePath = Path.Combine(directory, newFileName);

                try
                {
                    // 파일 이름 변경
                    File.Move(filePath, newFilePath);
                    Console.WriteLine($"파일 이름 변경: {fileName} -> {newFileName}");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"파일 이름 변경 실패: {fileName}, 오류: {ex.Message}");
                }
            }
        }

        Console.WriteLine("파일 이름 변경 작업이 완료되었습니다.");
    }
}

코드 설명

  1. 폴더 경로 설정
    folderPath 변수에 파일이 위치한 폴더 경로를 입력합니다.
  2. .exe 파일 필터링
    Directory.GetFiles(folderPath, "*.exe")를 사용하여 해당 폴더에서 .exe 확장자를 가진 모든 파일을 검색합니다.
  3. 파일 이름 변경 조건
    fileName.Contains("cam2") 조건으로 파일 이름에 cam2가 포함된 경우만 처리합니다.
  4. 파일 이름 변경
    File.Move 메서드를 사용하여 파일 이름을 cam1로 변경합니다.
  5. 예외 처리
    파일 이름 변경 중 오류가 발생할 경우 적절한 메시지를 출력합니다.

주의 사항

  • 변경 작업은 되돌릴 수 없으므로, 작업 전에 폴더 내용을 백업하세요.
  • 프로그램은 같은 폴더 내에서 이름이 충돌하지 않는다고 가정합니다. 이름이 중복될 경우 추가 처리가 필요합니다.
반응형