Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

c#

vb.net

wpf

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.ExecutablePath.ToString();

But with WPF I received this error from Visual Studio:

System.Window.Application does not contain a definition for ExecutablePath.

like image 358
Shahin Avatar asked Jun 26 '10 12:06

Shahin


5 Answers

System.Reflection.Assembly.GetExecutingAssembly().Location should work.

like image 187
Blorgbeard Avatar answered Nov 13 '22 00:11

Blorgbeard


Several alternatives:

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

System.AppDomain.CurrentDomain.BaseDirectory

Only in VB:

My.Application.Info.DirectoryPath
like image 28
Konrad Rudolph Avatar answered Nov 13 '22 01:11

Konrad Rudolph


this is useful for you: Application.ExecutablePath equals to:

Process.GetCurrentProcess().MainModule.FileName;
like image 21
dexiang Avatar answered Nov 13 '22 00:11

dexiang


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;
like image 3
scrat789 Avatar answered Nov 12 '22 23:11

scrat789


The following is applicable in the recent versions of .NET Core:

System.Environment.ProcessPath

This returns the path of the executable that started the currently running process.

like image 3
Salih Kavaf Avatar answered Nov 13 '22 01:11

Salih Kavaf