[C# 문법] C# 현재 디렉토리 위치 변경하는 방법 - Directory.SetCurrentDirectory 메서드

참조



소개

  • C#에서 파일 혹은 디렉터리를 다룰때, 현재 위치를 변경 혹은 설정해야 하는 경우들이 종종 있습니다.
  • 이럴 때, 유용하게 사용할 수 있는 메서드가 있는데요. Directory.SetCurrentDirectory 메서드를 이용하면 손쉽게 현재 디렉터리를 설정할 수 있습니다.


정의

  • 애플리케이션의 현재 작업 디렉터리를 지정된 디렉터리로 설정합니다.
public static void SetCurrentDirectory (string path);
  • 매개변수 path는 string 형식이고 현재 작업 디렉터리로 설정될 경로입니다.


예제 코드

using System;
using System.IO;
using System.Text.RegularExpressions;

namespace interfaceTest
{
    class Program
    {
        static void Main(string[] args)
        {
            string dir = @"C:\test";

            try
            {
                Directory.SetCurrentDirectory(dir);
            }
            catch(DirectoryNotFoundException e)
            {
                Console.WriteLine($"오류 발생 {e}");
            }

            Console.WriteLine($"상위 디렉터리 : {Directory.GetDirectoryRoot(dir)}");
            Console.WriteLine($"현재 디렉터리 : {Directory.GetCurrentDirectory()}");

            dir = @"C:\Demo\Test";

            Console.WriteLine();
            Console.WriteLine();

            try
            {
                Directory.SetCurrentDirectory(dir);
            }
            catch (DirectoryNotFoundException e)
            {
                Console.WriteLine($"오류 발생 {e}");
            }

            Console.WriteLine($"상위 디렉터리 : {Directory.GetDirectoryRoot(dir)}");
            Console.WriteLine($"현재 디렉터리 : {Directory.GetCurrentDirectory()}");
        }
    }
}


실행 결과

  • 다음과 같이 현재 디렉터리 위치를 자유롭게 설정할 수 있습니다.
  • 다만, 애플리케이션이 종료 되면 작업 디렉터리는 원래 위치로 복원 됩니다.
상위 디렉터리 : C:\
현재 디렉터리 : C:\test

상위 디렉터리 : C:\
현재 디렉터리 : C:\Demo\Test
728x90

이 글을 공유하기

댓글

Designed by JB FACTORY