C#/WPF

WPF 실행파일 위치 알아내는 법

기공이 2017. 12. 29. 10:37

사용자가 프로그램을 사용할 때 현재 실행파일(.exe 파일)이 있는 위치는 사용자마다, 혹은 매번 다를 수 있습니다.


그렇기에 상대경로가 필요한데, 현재 실행파일의 위치를 기준으로 한 상대적 경로입니다.


하지만 결국 파일에 접근하기 위해서는 절대 경로가 필요한데, 현재 실행파일의 위치를 알려주는 속성이 있습니다.



System.AppDomain.CurrentDomain.BaseDirectory 


※ "using System" 선언 시 AppDomain.CurrentDomain.BaseDirectory 로 가능.


string 형으로 현재 실행파일의 절대경로를 반환해주는데, 마지막\까지 포함된 상태로 반환됩니다. 




아래는 간단한 예제입니다.


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
private void ReadPeopleName()
{
    string[] lines = System.IO.File.ReadAllLines(AppDomain.CurrentDomain.BaseDirectory + "test.txt", Encoding.Default);
    // string array
    foreach (string temp in lines)
    {
        System.Console.WriteLine(temp);
    }
 
    /*
    string text = System.IO.File.ReadAllText(AppDomain.CurrentDomain.BaseDirectory + "test.txt", Encoding.Default);
    // string
    System.Console.WriteLine(text);
    */
}
cs