Getting the absolute path of the executable, using C#?
MSDN has an article that says to use System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase
; if you need the directory, use System.IO.Path.GetDirectoryName
on that result.
Or, there's the shorter Application.ExecutablePath
which "Gets the path for the executable file that started the application, including the executable name" so that might mean it's slightly less reliable depending on how the application was launched.
Getting the path of the executable file's current location
It isn't hard.
But it MIGHT depend on your target platform (which you haven't specified).
For .Net Core 1.x and .Net 5 or higher, I would use AppContext.BaseDirectory
Here are some other alternatives for various environments over the years:
6 ways to get the current directory in C#, August 17,
2010
AppDomain.CurrentDomain.BaseDirectory
This is the best option all round. It will give you the base directory for class libraries,
including those in ASP.NET applications.Directory.GetCurrentDirectory()
Note: in .NET Core this is the current best practice. The details below relate to the .NET Framework
4.5 and below.This does an interop call using the winapi GetCurrentDirectory call
inside kernel32.dll, which means the launching process’ folder will
often be returned. Also as the MSDN documents say, it’s not guaranteed
to work on mobile devices.Environment.CurrentDirectory
This simply calls Directory.GetCurrentDirectory()Assembly.Location
This would be called using
this.GetType().Assembly.Location
This returns the full path to the calling assembly, including the
assembly name itself. If you are calling a separate class library,
then its base directory will be returned, such “C:\myassembly.dll” -
depending obviously on which Assembly instance is being used.Application.StartupPath
This is inside the System.Windows.Forms namespace, so is typically used in window forms application only.Application.ExecutablePath
The same as Application.StartupPath, however this also includes the application name, such as “myapp.exe”
How to get the Full Path of a File?
The documentation for Get-Command says:
Get-Command * gets all types of commands, including all of the non-PowerShell files in the Path environment variable ($env:Path), which it lists in the Application command type.
So we will need to get the Path
environment variable and iterate over the directories it lists, looking for files with extensions that indicate the file is a program, for example "*.com" and "*.exe".
The problem with the Path environment variable is that it can become polluted with non-existent directories, so we will have to check for those.
The case of the filename and extension don't matter, so case-insensitive comparisons need to be made.
static void ShowPath(string progName)
{
var extensions = new List<string> { ".com", ".exe" };
string envPath = Environment.GetEnvironmentVariable("Path");
var dirs = envPath.Split(new char[] { ';' }, StringSplitOptions.RemoveEmptyEntries);
foreach (string d in dirs.Where(f => Directory.Exists(f)))
{
foreach (var f in (Directory.EnumerateFiles(d).
Where(thisFile => extensions.Any(h => Path.GetExtension(thisFile).Equals(h, StringComparison.InvariantCultureIgnoreCase)))))
{
if (Path.GetFileNameWithoutExtension(f).Equals(progName, StringComparison.InvariantCultureIgnoreCase))
{
Console.WriteLine(f);
return;
}
}
}
Console.WriteLine("Not found.");
}
static void Main(string[] args)
{
ShowPath("calc");
Console.ReadLine();
}
Output:
C:\WINDOWS\system32\calc.exe
There is always the possibility that the current user does not have permission to list the files from somewhere in the path, so checks should be added for that. Also, you might want to use StringComparison.CurrentCultureIgnoreCase
for the comparison.
get path for my .exe
System.Reflection.Assembly.GetEntryAssembly().Location;
Find the full path of process
there is a easier way, import System.Diagnostics
then write following code,
public bool ProcessIsRun()
{
Process[] proc = Process.GetProcesses();
Return proc.Any(m => m.ProcessName.Contains("Your process name") && m.Modules[0].FileName == "Your File Path" );
}
How can I get the application's path in a .NET console application?
System.Reflection.Assembly.GetExecutingAssembly()
.Location
1
Combine that with System.IO.Path.GetDirectoryName
if all you want is the directory.
1As per Mr.Mindor's comment:
System.Reflection.Assembly.GetExecutingAssembly().Location
returns where the executing assembly is currently located, which may or may not be where the assembly is located when not executing. In the case of shadow copying assemblies, you will get a path in a temp directory.System.Reflection.Assembly.GetExecutingAssembly().CodeBase
will return the 'permanent' path of the assembly.
How to get the full path of running process?
using System.Diagnostics;
var process = Process.GetCurrentProcess(); // Or whatever method you are using
string fullPath = process.MainModule.FileName;
//fullPath has the path to exe.
There is one catch with this API, if you are running this code in 32 bit application, you'll not be able to access 64-bit application paths, so you'd have to compile and run you app as 64-bit application (Project Properties → Build → Platform Target → x64).
Related Topics
Null or Default Comparison of Generic Argument in C#
Why Does Calling a Method in My Derived Class Call the Base Class Method
Sort Observablecollection<String> Through C#
C# - Approach for Saving User Settings in a Wpf Application
How to Set the Timeout for a Tcpclient
Advantages of Cache VS Session
How to Call .Net Methods from Excel Vba
Resharper Wpf Error: "Cannot Resolve Symbol "Myvariable" Due to Unknown Datacontext"
Embedding One Dll Inside Another as an Embedded Resource and Then Calling It from My Code
How to Automatically Scroll to the Bottom of a Multiline Text Box
How to Validate Azure Ad Security Token
How to Make Multi-Language App in Winforms
Simple State MAChine Example in C#