문제

찾으려면 어떻게 응용 프로그램의 경로를 콘솔 프로그램?

Windows Forms, 사용할 수 있습니다 Application.StartupPath 경우 현재의 경로를 찾지만,이하지 않는 것에서 사용할 수 있 콘솔 응용 프로그램입니다.

도움이 되었습니까?

해결책

System.Reflection.Assembly.GetExecutingAssembly().Location1

그것을 결합하십시오 System.IO.Path.GetDirectoryName 당신이 원하는 것은 디렉토리입니다.

1Mr.Mindor의 의견에 따라 :
System.Reflection.Assembly.GetExecutingAssembly().Location 실행 어셈블리가 현재 위치한 위치에 반환되며, 이는 실행되지 않을 때 어셈블리가 위치하거나 위치하지 않을 수 있습니다. 섀도우 복사 어셈블리의 경우 임시 디렉토리에 경로가 표시됩니다. 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 프로그램이 매우 적은 Windows 프로그램 이이 기발한 것을 사용하지만 (나는 나 자신을 모릅니다)"라고 말합니다. 그래서 '스푸핑'할 수 있습니다. GetCommandLineArgs, 그러나 우리는 콘솔 응용 프로그램에 대해 이야기하고 있습니다. 콘솔 앱은 일반적으로 빠르고 더럽습니다. 그래서 이것은 내 키스 철학에 맞습니다.

ASP.NET 웹 앱에 관심이있는 사람이라면 다음은 세 가지 다른 방법의 결과입니다

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)

대신 이것을 사용할 수 있습니다.

System.Environment.CurrentDirectory

콘솔 애플리케이션의 경우 다음을 시도 할 수 있습니다.

System.IO.Directory.GetCurrentDirectory();

출력 (내 로컬 기계에서) :

C : users XXXXXXX Documents Visual Studio 2012 Projects ImageHandler GetDir bin Debug

또는 시도 할 수 있습니다 (결국 추가 백 슬래시가 있습니다).

AppDomain.CurrentDomain.BaseDirectory

산출:

C : users XXXXXXX Documents Visual Studio 2012 Projects ImageHandler GetDir bin Debug

이 코드를 사용하고 해결책을 얻었습니다.

AppDomain.CurrentDomain.BaseDirectory

.NET 코어 호환 방법을 찾고 있다면 사용하십시오.

System.AppContext.BaseDirectory

이는 .NET 프레임 워크 4.6 및 .NET Core 1.0 (및 .NET Standard 1.3)에 도입되었습니다. 보다: AppContext.basedirectory 속성.

에 따르면 이 페이지,

이것은 .NET Core의 AppDomain.currentDomain.basedirectory를 선호하는 대체품입니다.

나는 사용했다

System.AppDomain.CurrentDomain.BaseDirectory

응용 프로그램 폴더와 관련된 경로를 찾고 싶을 때. 이는 ASP.NET 및 WinForm 응용 프로그램 모두에서 작동합니다. 또한 System.Web Assemblies에 대한 참조가 필요하지 않습니다.

프로젝트 참조에 간단히 추가 할 수 있습니다 System.Windows.Forms 그런 다음 사용하십시오 System.Windows.Forms.Application.StartupPath 평소와 같이.

따라서 더 복잡한 방법이나 반사를 사용할 필요가 없습니다.

exe가 두 번 클릭하여 호출되면 이것을 사용합니다.

var thisPath = System.IO.Directory.GetCurrentDirectory();

내 말은, 왜 AP/Invoke 메소드가 아닌가?

    using System;
    using System.IO;
    using System.Runtime.InteropServices;
    using System.Text;
    public class AppInfo
    {
            [DllImport("kernel32.dll", CharSet = CharSet.Auto, ExactSpelling = false)]
            private static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
            private static HandleRef NullHandleRef = new HandleRef(null, IntPtr.Zero);
            public static string StartupPath
            {
                get
                {
                    StringBuilder stringBuilder = new StringBuilder(260);
                    GetModuleFileName(NullHandleRef, stringBuilder, stringBuilder.Capacity);
                    return Path.GetDirectoryName(stringBuilder.ToString());
                }
            }
    }

Application.StartupPath :

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");

다음 줄은 응용 프로그램 경로를 제공합니다.

var applicationPath = Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName)

위의 솔루션은 다음 상황에서 제대로 작동합니다.

  • 간단한 앱
  • 어셈블리 .getEntryAssembly ()가 null을 반환하는 다른 도메인에서
  • DLL은 내장 리소스에서 바이트 배열로로드되고 AppDomain에 Assuctly.Load (bytearrayofembeddeddll)로로드됩니다.

Assembly.GetEntryAssembly().Location 또는 Assembly.GetExecutingAssembly().Location

함께 사용합니다 System.IO.Path.GetDirectoryName() 디렉토리 만 얻습니다.

경로 GetEntryAssembly() 그리고 GetExecutingAssembly() 대부분의 경우 디렉토리가 동일하지만 다를 수 있습니다.

와 함께 GetEntryAssembly() 당신은 이것이 돌아올 수 있다는 것을 알고 있어야합니다 null 입력 모듈이 관리되지 않은 경우 (예 : C ++ 또는 VB6 실행 가능). 이 경우 사용할 수 있습니다 GetModuleFileName Win32 API에서 :

[DllImport("kernel32.dll", CharSet = CharSet.Auto)]
public static extern int GetModuleFileName(HandleRef hModule, StringBuilder buffer, int length);
AppDomain.CurrentDomain.BaseDirectory

제 3 자 참조 파일을 설치 패키지로 참조하기 위해 문제를 해결합니다.

vb.net에서

My.Application.Info.DirectoryPath

나를 위해 작동합니다 (응용 프로그램 유형 : 클래스 라이브러리). C#에 대해 확실하지 않습니다 ... 파일 이름이없는 경로를 문자열로 반환합니다.

아무도 이러한 방법은 작업에서 특별한 경우처럼을 사용하여 심볼릭 링크 exe,그들은 그 반환의 위치를 링크하지 않는 실제 exe.

그래서 사용할 수 있는 QueryFullProcessImageName 의 주위에 얻을:

using System;
using System.IO;
using System.Runtime.InteropServices;
using System.Text;
using System.Diagnostics;

internal static class NativeMethods
{
    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern bool QueryFullProcessImageName([In]IntPtr hProcess, [In]int dwFlags, [Out]StringBuilder lpExeName, ref int lpdwSize);

    [DllImport("kernel32.dll", SetLastError = true)]
    internal static extern IntPtr OpenProcess(
        UInt32 dwDesiredAccess,
        [MarshalAs(UnmanagedType.Bool)]
        Boolean bInheritHandle,
        Int32 dwProcessId
    );
}

public static class utils
{

    private const UInt32 PROCESS_QUERY_INFORMATION = 0x400;
    private const UInt32 PROCESS_VM_READ = 0x010;

    public static string getfolder()
    {
        Int32 pid = Process.GetCurrentProcess().Id;
        int capacity = 2000;
        StringBuilder sb = new StringBuilder(capacity);
        IntPtr proc;

        if ((proc = NativeMethods.OpenProcess(PROCESS_QUERY_INFORMATION | PROCESS_VM_READ, false, pid)) == IntPtr.Zero)
            return "";

        NativeMethods.QueryFullProcessImageName(proc, 0, sb, ref capacity);

        string fullPath = sb.ToString(0, capacity);

        return Path.GetDirectoryName(fullPath) + @"\";
    }
}

이 간단한 코드 라인을 시도하십시오.

 string exePath = Path.GetDirectoryName( Application.ExecutablePath);

다른 해결책은 현재 경로를 가리키는 상대 경로를 사용하는 것입니다.

Path.GetFullPath(".")

.NET Core Reflection에서 제공 한 로컬 경로를 사용 가능한 System.io 경로로 변환 한 사람은 아무도 없었습니다. 여기에 내 버전이 있습니다.

public static string GetApplicationRoot()
{
   var exePath = new Uri(System.Reflection.
   Assembly.GetExecutingAssembly().CodeBase).LocalPath;

   return new FileInfo(exePath).DirectoryName;

}

이렇게하면 코드가있는 위치에 대한 전체 "C : xxx xxx"형식 경로를 반환합니다.

실행 가능한 경로를 얻는 방법에는 여러 가지가 있습니다. 우리가 사용해야하는 경로는 우리의 요구에 따라 다릅니다. 여기서는 다른 방법에 대해 논의하는 링크가 있습니다.

응용 프로그램 실행 경로를 얻는 다양한 방법

다음은 함께 작동하는 신뢰할 수있는 솔루션입니다 32 비트 그리고 64 비트 응용 프로그램.

이 참조 추가 :

System.diagnostics 사용;

System.Management 사용;

이 방법을 프로젝트에 추가하십시오.

public static string GetProcessPath(int processId)
{
    string MethodResult = "";
    try
    {
        string Query = "SELECT ExecutablePath FROM Win32_Process WHERE ProcessId = " + processId;

        using (ManagementObjectSearcher mos = new ManagementObjectSearcher(Query))
        {
            using (ManagementObjectCollection moc = mos.Get())
            {
                string ExecutablePath = (from mo in moc.Cast<ManagementObject>() select mo["ExecutablePath"]).First().ToString();

                MethodResult = ExecutablePath;

            }

        }

    }
    catch //(Exception ex)
    {
        //ex.HandleException();
    }
    return MethodResult;
}

이제 그렇게 사용하십시오.

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

프로세스의 ID를 알고 있다면이 방법은 해당 ExecutePath를 반환합니다.

관심있는 사람들을 위해 추가 :

Process.GetProcesses() 

... 현재 실행중인 모든 프로세스의 배열을 제공 할 것입니다.

Process.GetCurrentProcess()

... 현재 프로세스와 함께 정보 (예 : ID 등)와 함께 현재 프로세스를 제공하고 제한된 통제 예를 들어 킬 등을 제공합니다.*

Solution Explorer를 사용하여 프로젝트 내에서 폴더 이름을 자원으로 만들 수 있다면 리소스 내에 파일을 붙여 넣을 수 있습니다.

private void Form1_Load(object sender, EventArgs e) {
    string appName = Environment.CurrentDirectory;
    int l = appName.Length;
    int h = appName.LastIndexOf("bin");
    string ll = appName.Remove(h);                
    string g = ll + "Resources\\sample.txt";
    System.Diagnostics.Process.Start(g);
}
라이센스 : CC-BY-SA ~와 함께 속성
제휴하지 않습니다 StackOverflow
scroll top