[C#] .NET 콘솔 응용 프로그램에서 응용 프로그램의 경로를 얻으려면 어떻게해야합니까?

콘솔 응용 프로그램에서 응용 프로그램의 경로를 어떻게 찾습니까?

에서 윈도우 폼 , 내가 사용할 수있는 Application.StartupPath현재 경로를 찾을 수 있지만, 이것은 콘솔 응용 프로그램에서 사용할 수하지 않는 것 같습니다.



답변

System.Reflection.Assembly.GetExecutingAssembly(). 1Location

System.IO.Path.GetDirectoryName원하는 것이 디렉토리이면 결합 하십시오.

1 Mr.Mindor의 의견에 따라 :
System.Reflection.Assembly.GetExecutingAssembly().Location 실행중인 조립품이 현재 위치한 곳을 반환합니다. 섀도 복사 어셈블리의 경우 temp 디렉토리에 경로가 있습니다. System.Reflection.Assembly.GetExecutingAssembly().CodeBase어셈블리의 ‘영구적’경로를 반환합니다.


답변

다음 코드를 사용하여 현재 응용 프로그램 디렉토리를 얻을 수 있습니다.

AppDomain.CurrentDomain.BaseDirectory


답변

응용 프로그램의 디렉토리를 찾는 데는 두 가지 옵션이 있습니다. 선택하는 것은 목적에 따라 다릅니다.

// to get the location the assembly is executing from
//(not necessarily where the it normally resides on disk)
// in the case of the using shadow copies, for instance in NUnit tests, 
// this will be in a temp directory.
string path = System.Reflection.Assembly.GetExecutingAssembly().Location;

//To get the location the assembly normally resides on disk or the install directory
string path = System.Reflection.Assembly.GetExecutingAssembly().CodeBase;

//once you have the path you get the directory with:
var directory = System.IO.Path.GetDirectoryName(path);


답변

아마 약간 늦었지만 언급 할 가치가 있습니다.

Environment.GetCommandLineArgs()[0];

또는 디렉토리 경로 만 가져 오는 것이 더 정확합니다.

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

편집하다:

꽤 많은 사람들이 GetCommandLineArgs프로그램 이름을 반환한다고 보장하지는 않습니다. 명령 행의 첫 번째 단어는 규칙에 따른 프로그램 이름 입니다.를 참조하십시오 . 이 기사는 “극소의 Windows 프로그램이이 문제를 사용하지만 (내 자신을 전혀 모른다)”라고 기술하고있다. 따라서 ‘스푸핑’이 가능 GetCommandLineArgs하지만 콘솔 응용 프로그램에 대해 이야기하고 있습니다. 콘솔 앱은 일반적으로 빠르고 더럽습니다. 그래서 이것은 나의 KISS 철학과 맞습니다.


답변

asp.net 웹앱에 관심이있는 사람 다음은 3 가지 방법의 결과입니다.

protected void Application_Start(object sender, EventArgs e)
{
  string p1 = System.IO.Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
  string p2 = System.Web.Hosting.HostingEnvironment.ApplicationPhysicalPath;
  string p3 = this.Server.MapPath("");
  Console.WriteLine("p1 = " + p1);
  Console.WriteLine("p2 = " + p2);
  Console.WriteLine("p3 = " + p3);
}

결과

p1 = C:\Windows\Microsoft.NET\Framework64\v4.0.30319\Temporary ASP.NET Files\root\a897dd66\ec73ff95\assembly\dl3\ff65202d\29daade3_5e84cc01
p2 = C:\inetpub\SBSPortal_staging\
p3 = C:\inetpub\SBSPortal_staging

앱이 실제로 “C : \ inetpub \ SBSPortal_staging”에서 실행 중이므로 첫 번째 솔루션은 웹 앱에는 적합하지 않습니다.


답변

위의 답변은 내가 필요한 것의 90 %이지만 나에게 일반적인 경로 대신 Uri를 반환했습니다.

MSDN 포럼 게시물에 설명 된 것처럼 URI 경로를 일반 파일 경로로 변환하는 방법은 무엇입니까? , 나는 다음을 사용했다.

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;


답변

이 작업을 수행하려고 할 수 있습니다.

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)