Search code examples
c#.netcmdexeinvoke

How do Environment.CurrentDirectory work?


static void Main(string[] args)
{
    Console.WriteLine(Environment.CurrentDirectory);

    Console.ReadLine();
}

The code is very simple, but accidentally it raised a question. If I press the "Run" button, I will get the output like:

C:\Users\Admin\source\repos\FeaturesTest\ConsoleApp1\bin\Debug

But if I invoke this program with cmd.exe or Powershell, the output will be the current directory of the console:

Example 1:
PS C:\Users\Admin> C:\Users\Admin\source\repos\FeaturesTest\ConsoleApp1\bin\Debug\ConsoleApp1.exe
C:\Users\Admin

PS C:\Users\Admin> _

Example 2:
PS C:\Users\Admin\Desktop> C:\Users\Admin\source\repos\FeaturesTest\ConsoleApp1\bin\Debug\ConsoleApp1.exe
C:\Users\Admin\Desktop

PS C:\Users\Admin\Desktop> _

If I invoke this program with another, the output will be the working directory of the latter (which invoke the former):

The code of ConsoleApp2 (the caller):

        static void Main(string[] args)
        {
            Process.Start(@"C:\Users\Admin\source\repos\FeaturesTest\ConsoleApp1\bin\Debug\ConsoleApp1.exe");
        }
The output of ConsoleApp1 (the called program, because ConsoleApp2 don't have output):

        C:\Users\Admin\source\repos\FeaturesTest\ConsoleApp2\bin\Debug

So, I repeat the question: How do Environment.CurrentDirectory work? I just want to know it.
Thank you.


Solution

  • By definition, if this process starts in the root directory of a local or network drive, the value of this property is the drive name followed by a trailing slash (for example, "C:"). If this process starts in a subdirectory, the value of this property is the drive and subdirectory path, without a trailing slash (for example, "C:\mySubDirectory").

    https://learn.microsoft.com/en-us/dotnet/api/system.environment.currentdirectory?view=net-5.0

    Enviroment.CurrentDirectory will give you the directory where the application is invoked. If you invoke the executable from a PowerShell, in C:\ the app will be wrapped inside this shell, there's no need to instantiate a new shell... If you double click the .exe file will prompt a new shell to run the application, so the directory it's where the .exe is.

    Check also this question to check other methods to get a directory of a running application.

    Best way to get application folder path