Search code examples
c#.net-coreworking-directory

Set current working directory on exit (.NET Core)


I would like to have my application set the current working directory after my application is ran, meaning that, for example:

$ pwd
/my/directory
$ dotnet MyApp.dll
$ pwd
/another/place/somewhere

How can I do that in C# using .NET Core in a cross-platform way?

I looked at Environment.CurrentDirectory and Directory.SetCurrentDirectory but for both of them the working directory is reset to its original state when the application exits, as indicated in the documentation for Directory.SetCurrentDirectory.

When the application terminates, the working directory is restored to its original location (the directory where the process was started).

https://learn.microsoft.com/en-us/dotnet/api/system.io.directory.setcurrentdirectory?view=netframework-4.7.2#remarks


Solution

  • You can't.

    The current working directory is a property of each process.

    To change it in the terminal, you need to find a way to tell the terminal to do it. A program that the terminal launches can change its own current directory, but not that of the calling terminal.

    This is why cd is a built-in in shells. If it was an external program, it couldn't change the working directory of the shell/terminal.