C#/개발

C# 파일 이름 변경

푸코잇 2024. 1. 13. 00:10
728x90

C# 파일 이름 변경

C#에서 파일 이름을 변경할 때 File 클래스의 Move 메서드를 사용하면 된다.

 

// Move 메서드 함수원형
public static void Move(string sourceFileName, string destFileName);

 

  • sourceFileName : 이동할 파일의 이름으로 상대 또는 절대 경로가 포함될 수 있다.
  • destFileName : 파일에 대한 새 경로 및 이름으로 상대 또는 절대 경로가 포함될 수 있다.
예외 원인
System.IO.IOException sourceFileName을 찾을 수 없거나 destFileName이 이미 존재하는 경우
System.IO.PathTooLongException 경로 및 파일이름이 시스템에서 정의한 최대 길이를 초과한 경우
System.IO.DirectoryNotFoundException sourceFileName 또는 destFileName에 지정된 경로가 잘못된 경우
System.ArgumentNullException sourceFileName 또는 destFileName이 null인 경우
System.ArgumentException sourceFileName 또는 destFileName이 빈 문자열, 공백만을 포함하거나 System.IO.Path.InvalidPathChars에 정의되어있는 잘못된 문자를 포함하는 경우
System.UnauthorizedAccessException 호출자에게 필요한 권한이 없는 경우
System.NotSupportedException sourceFileName 또는 destFileName의 형식이 잘못된 경우

 

사용 방법

static void Main(string[] args)
{
    string srcPath = @"D:\Move\src.txt";
    string destPath = @"D:\Move\des.txt";

    try
    {
        // srcPath 파일이 존재하는지 체크
        if (File.Exists(srcPath))
        {
            // destPath가 이미 존재하는 경우 파일 삭제
            if(File.Exists(destPath))
            {
                File.Delete(destPath);
            }

            // 파일 이름 변경
            File.Move(srcPath, destPath);
        }
    }
    catch(Exception ex)
    {
        Console.WriteLine(ex);
    }
}

'C# > 개발' 카테고리의 다른 글

C# int to bool 변환하는 방법  (0) 2024.04.23
C# 경로가 디렉토리인지 파일인지 구분하는 방법  (0) 2024.02.02
C# 날짜 일수 차이 계산  (0) 2024.01.18
C# enum 순회  (0) 2024.01.08