source

WPF(C# 또는 vb.net)에서 응용 프로그램 실행 파일의 위치를 찾을 수 있습니까?

itover 2023. 4. 12. 22:17
반응형

WPF(C# 또는 vb.net)에서 응용 프로그램 실행 파일의 위치를 찾을 수 있습니까?

WPF(C# 또는 VB.Net)에서 애플리케이션 실행 파일의 위치를 찾으려면 어떻게 해야 합니까?

Windows 폼에서 이 코드를 사용했습니다.

Application.ExecutablePath.ToString();

그러나 WPF에서는 Visual Studio에서 다음 오류가 발생했습니다.

System. Window.응용 프로그램에 ExecutablePath에 대한 정의가 없습니다.

System.Reflection.Assembly.GetExecutingAssembly().Location작동해야 합니다.

몇 가지 대안이 있습니다.

Directory.GetParent(Assembly.GetExecutingAssembly().Location)

System.AppDomain.CurrentDomain.BaseDirectory

VB에서만:

My.Application.Info.DirectoryPath

응용 프로그램입니다.ExecutivePath는 다음과 같습니다.

Process.GetCurrentProcess().MainModule.FileName;

의 최신 버전에는 다음 사항이 적용됩니다.NET 코어:

System.Environment.ProcessPath

현재 실행 중인 프로세스를 시작한 실행 파일의 경로를 반환합니다.

코드가 라이브러리에 있는 경우 실행 어셈블리는 DLL일 수 있습니다.

var executingAssembly = Assembly.GetExecutingAssembly(); //MyLibrary.dll
var callingAssembly = Assembly.GetCallingAssembly(); //MyLibrary.dll
var entryAssembly = Assembly.GetEntryAssembly(); //WpfApp.exe or MyLibrary.dll

그래서 제가 찾은 최선의 방법은 (C#)입니다.

var wpfAssembly = (AppDomain.CurrentDomain
                .GetAssemblies()
                .Where(item => item.EntryPoint != null)
                .Select(item => 
                    new {item, applicationType = item.GetType(item.GetName().Name + ".App", false)})
                .Where(a => a.applicationType != null && typeof(System.Windows.Application)
                    .IsAssignableFrom(a.applicationType))
                    .Select(a => a.item))
            .FirstOrDefault();

이 경우 어셈블리의 위치를 확인할 수 있습니다.

var location = wpfAssembly.Location;

이게 제가 쓰는 거예요.디버거에서도 동작합니다.

using System.IO;
using System.Diagnostics;

public static string GetMyBinDirectory()
{
    return Path.GetDirectoryName(Process.GetCurrentProcess().MainModule.FileName);
}

Process 및 Process Module과 같은 강력한 클래스를 사용합니다.

Environment.CurrentDirectoryexe 파일의 상위 디렉토리를 반환합니다.

다음은 다른 답변에 따라 경로에서 실행 파일 이름을 삭제하고 결과를 일부 하위 폴더 및 파일 이름과 결합하는 방법을 보여 주는 예시는 다음과 같습니다.

Hotspotizer 업데이트 버전(http://github.com/birbilis/Hotspotizer),에서 다음 코드를 사용하여 시작 시 제스처 컬렉션 파일(Library\Default.hsjson에 있는 경우)을 로드하는 지원을 추가했습니다.

const string GESTURE_COLLECTION_LIBRARY_PATH = "Library"
const string DEFAULT_GESTURE_COLLECTION = "Default.hsjson"

//...

LoadGestureCollection(
  Path.Combine(Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location),
  GESTURE_COLLECTION_LIBRARY_PATH,
  DEFAULT_GESTURE_COLLECTION));

언급URL : https://stackoverflow.com/questions/3123870/find-the-location-of-my-applications-executable-in-wpf-c-or-vb-net

반응형