0

I am trying to take in user input and have it act as a command prompt command. The following code takes the user input and processes it as a command prompt command:

System.Diagnostics.Process process = new System.Diagnostics.Process();
Console.WriteLine(process.StartInfo.WorkingDirectory);

process.StartInfo = new System.Diagnostics.ProcessStartInfo()
{
    UseShellExecute = false,
    CreateNoWindow = true,
    WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden,
    FileName = "cmd.exe",
    Arguments = "/C"+textBox1.Text, // takes the user input at executes it with the command prompt
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    WorkingDirectory = @"C:\Users\Me\Desktop"
};
Console.WriteLine(process.StartInfo.WorkingDirectory); // print the working directory
process.Start();

My code works well until I want to do multiple commands. The code above is called every time the user types a command and hits enter. But if the user tries to enter a second command, it will reset the working directory. A user may want to change the path with this command: cd C:/users/name/Desktop and then make a folder with mkdir projects. However, this code doesn't work because after each command, it defaults the working directory to one that the app is stored in. It created the projects folder in the same path that it defaults to with each command. Is there any way that the working directory doesn't default to the same path with each command?

  • You can do something like this: [How do I get output from a command to appear in a control on a Form in real-time?](https://stackoverflow.com/a/51682585/7444103). Read the notes and the comments in code. – Jimi Feb 03 '21 at 17:30
  • Thank You! That is very useful! – user9719238713 Feb 03 '21 at 17:48
  • If you decide to use that code, read the notes about the `SynchronizingObject`: you don't need to `BeginInvoke()`, that's used to show that the events are usually raised in ThreadPool Threads, but you can marshal the events to the UI Thread setting that property (and you should do it, if you just need to let a user enter commands). – Jimi Feb 03 '21 at 17:53
  • You may look at `Environment.CurrentDirectory` property – Pavel Anikhouski Feb 03 '21 at 20:35

0 Answers0