Find the location of my application's executable in WPF (C# or vb.net)?

前端 未结 7 1368
借酒劲吻你
借酒劲吻你 2020-12-08 04:02

How can I find the location of my application\'s executable in WPF (C# or VB.Net)?

I\'ve used this code with windows forms:

Application.ExecutablePat         


        
7条回答
  •  北荒
    北荒 (楼主)
    2020-12-08 04:24

    The executing assembly can be a DLL if the code is located in a library:

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

    So the best way I found is (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();
    

    So in your case, you can find location of the assembly :

    var location = wpfAssembly.Location;
    

提交回复
热议问题