1130

How do I find the application's path in a console application?

In Windows Forms, I can use Application.StartupPath to find the current path, but this doesn't seem to be available in a console application.

2
  • 7
    Do you install .NET Framework on target (Client, Development) machine? if your answer is true; So, you can add a reference to System.Windows.Forms.dll and use Application.StartupPath! This is the best way if you want to drop away further future exceptions! Mar 13, 2015 at 2:23
  • AppDomain.BaseDirectory is app directory. Be aware that application can behave different in VS env and Win env. But AppDomain should be same not as application.path but i hope that this is not only for IIS.
    – Mertuarez
    Apr 29, 2016 at 13:11

30 Answers 30

1348

System.Reflection.Assembly.GetExecutingAssembly().Location1

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.

19
  • 264
    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 'permenant' path of the assembly.
    – Mr.Mindor
    Oct 14, 2011 at 18:13
  • 17
    @SamGoldberg: That depend on how it is used: stackoverflow.com/q/1068420/391656 . Or you can ... new Uri(System.Reflection.Assembly.GetExecutingAssembly().CodeBase).LocalPath
    – Mr.Mindor
    Aug 30, 2012 at 21:31
  • 47
    GetExecutingAssembly returns assembly that contains the code that is currently executing. This may not necessarily be the console .exe assembly. It may be an assembly that has been loaded from a totally different location. You will have to use GetEntryAssembly! Also note that CodeBasemight not be set when the assembly is in the GAC. The better alternative is AppDomain.CurrentDomain.BaseDirectory.
    – bitbonk
    Aug 6, 2015 at 14:41
  • 4
    if you call dll, System.Reflection.Assembly.GetExecutingAssembly().CodeBase will get "file:///C:/Windows/Microsoft.NET/Framework64/v4.0.30319/mscorlib.dll"
    – raidsan
    Dec 26, 2017 at 5:03
  • 5
    @farosch: Application doesn't exist for console applications.
    – Sam Axe
    Apr 4, 2018 at 22:57
477

You can use the following code to get the current application directory.

AppDomain.CurrentDomain.BaseDirectory
9
  • 57
    Don't use this. The BaseDirectory can be set at runtime. It is not guaranteed to be correct (like the accepted answer is).
    – usr
    Jul 15, 2012 at 20:29
  • 4
    +1 This is likely the answer you want as it compensates for shadow copying. May 8, 2014 at 23:42
  • 4
    @usr What makes you think that BaseDirectory can be set at runtime? It only has a getter.
    – bitbonk
    Aug 6, 2015 at 14:43
  • 3
    @bitbonk it can be set at appdomain creation time.
    – usr
    Aug 6, 2015 at 14:43
  • 3
    Isn't it that BaseDirectory can be changed in a *.lnk file, in the "Start in:" field?
    – Alexander
    Jun 15, 2016 at 14:46
212
+50

You have two options for finding the directory of the application, which you choose will depend on your purpose.

// To get the location the assembly is executing from
// (not necessarily where it normally resides on disk).
// In the case of 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);
6
  • 3
    Just wanted to say, obviously there are many more than 2 options by how many other choices are posted...
    – vapcguy
    Jun 27, 2016 at 17:23
  • 21
    If whatever you're trying to do with said path doesn't support URI format, use var localDirectory = new Uri(directory).LocalPath; Sep 27, 2016 at 13:25
  • This is just wrong. What is the executable is not a .NET assembly at all? The right answer is to check the environment and inspect the command line.
    – mark
    Apr 13, 2018 at 13:17
  • 2
    @Ukuma.Scott This doesn't work if the path contains & or #
    – MatsW
    Feb 7, 2019 at 9:12
  • @mark Would you please tell what the actual code is ?
    – Grace
    Dec 9, 2022 at 11:03
99

Probably a bit late but this is worth a mention:

Environment.GetCommandLineArgs()[0];

Or more correctly to get just the directory path:

System.IO.Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]);

Edit:

Quite a few people have pointed out that GetCommandLineArgs is not guaranteed to return the program name. See The first word on the command line is the program name only by convention. The article does state that "Although extremely few Windows programs use this quirk (I am not aware of any myself)". So it is possible to 'spoof' GetCommandLineArgs, but we are talking about a console application. Console apps are usually quick and dirty. So this fits in with my KISS philosophy.

Edit It seems, from feedback, that most of the other solutions don't work when you are using a unit testing system. This sort of makes sense as the executable item is not your application but the testing system. I have not checked this out - so I could be completely wrong. If this is so, I will delete this edit.

10
  • 1
    @usr the situation you allude to is highly theoretical. In the context of a console application, it doesn't really make sense to use any other method. Keep it simple!
    – Steve Mc
    Jul 21, 2012 at 10:32
  • 1
    @usr mmm - looking at the taskmgr cmdline column sort of backs up what I'm saying. A few system services with just the exe name. Never mind. What I'm trying to say is that when developing a console application there is no need to make things more complicated than they need to be. Especially when we already have the information available. Now, if you are running a console application in such a way as to trick GetCommandLineArgs then you are already jumping through hoops and you would probably need to ask yourself if a console app is the right way to go.
    – Steve Mc
    Jul 22, 2012 at 8:54
  • 6
    Your "simple" solution involves two method calls. The "complicated" solution involves two method calls. No practical difference - except that the "simple" solution can give you the wrong answer under certain circumstances which aren't under your control when you're writing the program. Why take the risk? Use the other two method calls, and your program will be no more complicated but will be more reliable.
    – Chris
    Feb 22, 2013 at 14:53
  • 3
    Worked for my scenario, the other solutions did not, so thanks for providing another alternative :-) I was using ReSharper test runner to run an MS Unit test and the code I was testing needed a specific .dll to be in the executing directory...and Assembly.GetExecutingDirectory() weirdly returns a different result.
    – wallismark
    Mar 4, 2015 at 6:27
  • 1
    @Chris - to the defense of this answer. It works for unit tests, the GetEntryAssembly solution does not, because GetEntryAssembly returns null. The answers which propose GetExecutingAssembly are bogus, because they only return the executable if the executing assembly is the executable. This is not the simple, but the correct solution.
    – mark
    Apr 13, 2018 at 13:16
51

For anyone interested in asp.net web apps. Here are my results of 3 different methods

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);
}

result

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

the app is physically running from "C:\inetpub\SBSPortal_staging", so the first solution is definitely not appropriate for web apps.

0
47

The answer above was 90% of what I needed, but returned a Uri instead of a regular path for me.

As explained in the MSDN forums post, How to convert URI path to normal filepath?, I used the following:

// Get normal filepath of this assembly's permanent directory
var path = new Uri(
    System.IO.Path.GetDirectoryName(
        System.Reflection.Assembly.GetExecutingAssembly().CodeBase)
    ).LocalPath;
5
  • 1
    this works well also if the exe in question is a windows service and current directory returns C:\Windows\system32. The above code returns the actual location of the exe Feb 20, 2015 at 11:32
  • Except if you then try to do something like File.CreateDirectory(path), it will give you the exception that it doesn't allow URI paths...
    – vapcguy
    Jun 27, 2016 at 17:26
  • 2
    Unfortunately this is doesn't work for paths that contain a fragment identifier (the # character). The identifier and everything following it is truncated from the resulting path.
    – bgfvdu3w
    Feb 2, 2018 at 8:07
  • Why don't you swap new Uri and System.IO.Path.GetDirectoryName? That gives you a normal path string instead of a Uri.
    – Timo
    Nov 5, 2018 at 16:50
  • I find this the best one. This same approach has worked reliably for me in any environment. In production, debugging locally, unit testing... Want to open a content file that you included ("content - copy if newer") in a unit test? It's there.
    – Timo
    Nov 5, 2018 at 16:54
41

If you are looking for a .NET Core compatible way, use

System.AppContext.BaseDirectory

This was introduced in .NET Framework 4.6 and .NET Core 1.0 (and .NET Standard 1.3). See: AppContext.BaseDirectory Property.

According to this page,

This is the prefered replacement for AppDomain.CurrentDomain.BaseDirectory in .NET Core

2
32

You may be looking to do this:

System.IO.Path.GetDirectoryName(
    System.Reflection.Assembly.GetExecutingAssembly().GetName().CodeBase)
1
  • 1
    Note this brought back a URI, which isn't supported in all cases. Oct 8, 2020 at 20:43
29

you can use this one instead.

System.Environment.CurrentDirectory
2
  • This will get the folder of the executable though
    – Iain
    Nov 15, 2012 at 20:27
  • 1
    This can be changed in number of ways(shortcut settings etc)... better to NOT use it. Nov 19, 2019 at 20:09
22

For Console Applications, you can try this:

System.IO.Directory.GetCurrentDirectory();

Output (on my local machine):

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug

Or you can try (there's an additional backslash in the end):

AppDomain.CurrentDomain.BaseDirectory

Output:

c:\users\xxxxxxx\documents\visual studio 2012\Projects\ImageHandler\GetDir\bin\Debug\

1
  • 1
    "The BaseDirectory can be set at runtime. It is NOT guaranteed to be correct" Nov 19, 2019 at 20:09
18

I have used this code and get the solution.

AppDomain.CurrentDomain.BaseDirectory
15

Following line will give you an application path:

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

Above solution is working properly in the following situations:

  • simple app
  • in another domain where Assembly.GetEntryAssembly() would return null
  • DLL is loaded from Embedded resources as a byte array and loaded to AppDomain as Assembly.Load(byteArrayOfEmbeddedDll)
  • with Mono's mkbundle bundles (no other methods work)
1
  • 2
    Under debugger on linux this returns: /usr/share/dotnet
    – Vladimir
    Mar 12, 2020 at 7:50
9

You can simply add to your project references System.Windows.Forms and then use the System.Windows.Forms.Application.StartupPath as usual .

So, not need for more complicated methods or using the reflection.

2
  • I used that one, and it works well. But one time I used the method having it in my unit test project. And of course, it failed because it was looking for my file in C:\PROGRAM FILES (X86)\MICROSOFT VISUAL STUDIO 14.0\COMMON7\IDE\COMMONEXTENSIONS\MICROSOFT\TESTWINDOW
    – ainasiart
    Aug 31, 2017 at 19:09
  • @ainasiart so how do i get this to work while unit testing?? Dec 9, 2019 at 18:42
8

I have used

System.AppDomain.CurrentDomain.BaseDirectory

when I want to find a path relative to an applications folder. This works for both ASP.Net and winform applications. It also does not require any reference to System.Web assemblies.

0
7

I mean, why not a p/invoke method?

    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());
                }
            }
    }

You would use it just like the Application.StartupPath:

    Console.WriteLine("The path to this executable is: " + AppInfo.StartupPath + "\\" + System.Diagnostics.Process.GetCurrentProcess().ProcessName + ".exe");
2
  • 2
    Why p/invoke when there is so much .NET for this?
    – ProfK
    Mar 3, 2015 at 18:57
  • 7
    @user3596865 because it requries a hard dependency to Windows and is not compatible with DNX or Mono. And maybe there is a breaking change in future Windows Versions. So again: why we should use pinvoke here? Jan 20, 2016 at 10:05
7

I didn't see anyone convert the LocalPath provided by .Net Core reflection into a usable System.IO path so here's my version.

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

   return new FileInfo(exePath).DirectoryName;
       
}

This will return the full C:\\xxx\\xxx formatted path to where your code is.

1
  • I fail to understand how Uri(System.Reflection. Assembly.GetExecutingAssembly().CodeBase).LocalPath is any different then System.Reflection.Assembly.GetExecutingAssembly().CodeBase Can you elaborate?
    – RonC
    Dec 9, 2021 at 17:24
6

Assembly.GetEntryAssembly().Location or Assembly.GetExecutingAssembly().Location

Use in combination with System.IO.Path.GetDirectoryName() to get only the directory.

The paths from GetEntryAssembly() and GetExecutingAssembly() can be different, even though for most cases the directory will be the same.

With GetEntryAssembly() you have to be aware that this can return null if the entry module is unmanaged (ie C++ or VB6 executable). In those cases it is possible to use GetModuleFileName from the Win32 API:

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

I use this if the exe is supposed to be called by double clicking it

var thisPath = System.IO.Directory.GetCurrentDirectory();
2
  • 5
    This is not correct because you can get random directories in result.
    – amuliar
    Jul 3, 2013 at 10:58
  • this Command returns Environment.CurrentDirectory, which may be changed at runtime to any path, so it is not a reliable solution. Jan 11, 2019 at 3:41
6

in VB.net

My.Application.Info.DirectoryPath

works for me (Application Type: Class Library). Not sure about C#... Returns the path w/o Filename as string

0
6

For .NET 6 there's Environment.ProcessPath.

See https://learn.microsoft.com/en-us/dotnet/api/system.environment.processpath?view=net-6.0

5
  • While this link may answer the question, it is better to include the essential parts of the answer here and provide the link for reference. Link-only answers can become invalid if the linked page changes. - From Review Nov 25, 2021 at 1:38
  • 2
    @ErikMcKelvey They're giving a solution and a reference to the documentation that says that is in fact a solution. How would you reference a solution without using a link?
    – Scratte
    Nov 25, 2021 at 16:55
  • @Scratte He did not mean that the link should be left away; instead, he says ... and provide the link for reference. It is common sense here on SO that link-only answers may become useless very fast, because links targets tend to vanish fast. So indeed it's best to post the link, but additionally try to incorporate at least the most essential information from the page the link refers to.
    – Binarus
    Aug 24, 2022 at 8:45
  • 1
    @Binarus They did. They said ".NET 6 there's Environment.ProcessPath", which is the "essential part". That's all one needs to know to move on to a solution. The link is just a reference to "Environment.ProcessPath". It's extra, so people who don't need to google "Environment.ProcessPath". Did you click on the link? What exactly do you think should be copy'n'pasted from it?
    – Scratte
    Sep 2, 2022 at 18:10
  • Well, you're probably right in this case. I just was trying to explain what Erik McKelvey was meaning (in response to your first comment).
    – Binarus
    Sep 3, 2022 at 14:55
5
AppDomain.CurrentDomain.BaseDirectory

Will resolve the issue to refer the 3rd party reference files with installation packages.

1
  • 12
    This answer has already been suggested 5 years ago, even more than once.
    – P-L
    Aug 14, 2014 at 19:05
5

With .NET Core 3 and above you will get the .dll and not the .exe file. To get the .exe file path you can use.

var appExePath = Process.GetCurrentProcess().MainModule.FileName;
4

Try this simple line of code:

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

In .NET 6, my WPF app (<TargetFramework>net6.0-windows</TargetFramework>) returns the .dll file path for Assembly.GetEntryAssembly()!.Location instead of the .exe file. They introduced System.Environment.ProcessPath for this purpose:

var path = Environment.ProcessPath; // Note it may be null

Returns the path of the executable that started the currently executing process. Returns null when the path is not available.

See discussion for it here and here.

2

None of these methods work in special cases like using a symbolic link to the exe, they will return the location of the link not the actual exe.

So can use QueryFullProcessImageName to get around that:

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) + @"\";
    }
}
2

Path.GetDirectoryName(System.Diagnostics.Process.GetCurrentProcess().MainModule.FileName) Is the only one that has worked for me in every case I have tried.

1

The techniques, and pitfalls, keep changing. The below assumes you're running a .NET 6 console app on linux (on win/mac the results will follow a similar pattern, just replace /usr/share/ and /home/username/ with the standard locations for your OS).

Demo:

Console.WriteLine("Path.GetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName) = " + Path.GetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName));
Console.WriteLine("Path.GetDirectoryName(Environment.ProcessPath)                           = " + Path.GetDirectoryName(Environment.ProcessPath));
Console.WriteLine("Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)          = " + Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location));
Console.WriteLine("typeof(SomeType).Assembly.Location                                       = " + typeof(SomeType).Assembly.Location);
Console.WriteLine("Path.GetDirectoryName(Environment.GetCommandLineArgs()[0])               = " + Path.GetDirectoryName(Environment.GetCommandLineArgs()[0]));
Console.WriteLine("AppDomain.CurrentDomain.BaseDirectory                                    = " + AppDomain.CurrentDomain.BaseDirectory);
Console.WriteLine("System.AppContext.BaseDirectory                                          = " + System.AppContext.BaseDirectory);

Results:

Path.GetDirectoryName(Process.GetCurrentProcess()?.MainModule?.FileName) = /usr/share/dotnet
Path.GetDirectoryName(Environment.ProcessPath)                           = /usr/share/dotnet
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)          = /home/username/myproject/bin/Debug/net6.0
typeof(SomeType).Assembly.Location                                       = /home/username/myproject/bin/Debug/net6.0
Path.GetDirectoryName(Environment.GetCommandLineArgs()[0])               = /home/username/myproject/bin/Debug/net6.0
AppDomain.CurrentDomain.BaseDirectory                                    = /home/username/myproject/bin/Debug/net6.0/
System.AppContext.BaseDirectory                                          = /home/username/myproject/bin/Debug/net6.0/

Each approach has its own pros and cons - see the other answers to learn in which uses cases to use which approach.

I run my .NET 6 console app with dotnet myapp, so what works (reliably) for me is either of:

typeof(SomeType).Assembly.Location
// or
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location)
0

Here is a reliable solution that works with 32bit and 64bit applications.

Add these references:

using System.Diagnostics;

using System.Management;

Add this method to your project:

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;
}

Now use it like so:

int RootProcessId = Process.GetCurrentProcess().Id;

GetProcessPath(RootProcessId);

Notice that if you know the id of the process, then this method will return the corresponding ExecutePath.

Extra, for those interested:

Process.GetProcesses() 

...will give you an array of all the currently running processes, and...

Process.GetCurrentProcess()

...will give you the current process, along with their information e.g. Id, etc. and also limited control e.g. Kill, etc.*

0

I use this for console + net 6

Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location)
-5

You can create a folder name as Resources within the project using Solution Explorer,then you can paste a file within the Resources.

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);
}
1
  • 6
    Using Environment.CurrentDirectory is very wrong, don't use this! this path can change at runtime. Even at startup it is non-deterministic.
    – usr
    Jul 15, 2012 at 20:28

Not the answer you're looking for? Browse other questions tagged or ask your own question.