0

I want my program to change current directory exactly like Set-Location command. So my program executes, then I see a different directory in my command prompt.

This DOES NOT WORK:

Directory.SetCurrentDirectory(Scripts);
Environment.CurrentDirectory = Scripts;

This changes current directory for the executing process, not the executing shell directory.

What I see:

PS C:\Users\Test>test.exe
PS C:\Users\Test>

What I want is:

PS C:\Users\Test>test.exe
PS C:\Test>

Yep, I execute this from PowerShell, but I do not want a PowerShell script, I need my C# application to change the shell path for me, and then continue the same shell. Of course it should also work in cmd.exe.

I'd like to avoid creating a separate shell, instead I want my program to act as a shell command. If you curious it's a configuration manager, which should configure script directory according to a template name given as command argument, it should change the path to configured scripts directory.

Harry
  • 4,524
  • 4
  • 42
  • 81
  • 1
    You cant do that, your process only has write access to its own environment, it cant change it for another process - even the one that spawned it. – Alex K. Jul 29 '17 at 13:05
  • is this related to your question? https://stackoverflow.com/a/18875988/4301653 – raichiks Jul 29 '17 at 13:17
  • Have a look at this. https://msdn.microsoft.com/en-us/library/system.io.directory.setcurrentdirectory(v=vs.110).aspx Does your directory exist? You will get an exception if you try to change to a non existing directory – Oddmar Dam Jul 29 '17 at 13:40
  • OK, I get it, "no can't do", I already started to write my own shell, it's not that hard. I even made autocomplete, works fine. – Harry Jul 29 '17 at 16:51

1 Answers1

0

You cannot change the current directory of your parent process.

I implemented a GUI "change directory" utility for cmd.exe many years ago and I did it by using a batch file that executed my application and then read and applied the new directory path from a file written by the application. This works because the batch script runs inside the cmd.exe process and is able to change the current directory. I assume the same would be possible in PowerShell.

The batch file was something simple like this:

@echo off
call "c:\path\to\app.exe" "%temp%\newdir.txt"
if exist "%temp%\newdir.txt" for /F "usebackq tokens=*" %%A in ("%temp%\newdir.txt") do cd /D "%%~A"
Anders
  • 97,548
  • 12
  • 110
  • 164
  • It works from cmd.exe, but not in PowerShell. However it's not possible to change the current working directory from C# either using cmd.exe or PowerShell. So I think by now the answer for that question simply doesn't exists, or it's that it's impossible. – Harry Sep 04 '17 at 13:56