-1

I need to run command line from a c# program. I want to set the directory of the command line window. To do so, I am using the following code:

Process.Start("cmd", @"cd C:\Users\user1\Desktop");

When I run the c# program, a command line window is opened, but the directory is not set to C:\Users\user1\Desktop, meaning the command was not executed. What am I doing wrong?

  • See https://stackoverflow.com/questions/5047171/passing-an-argument-to-cmd-exe. I believe you would want to do "cmd /k C:\Users\user1\Desktop" – bgura Jul 18 '17 at 20:21
  • After the command changes the directory, what do you want to happen next? Window/Process stay open? Or the Window/Process exit? – Black Frog Jul 18 '17 at 20:37
  • _"the directory is not set"_ -- which directory is not set? The command you're executing will change the directory in the context of the command. But it's not going to affect the current directory of the process that launched that command, nor the current directory of any other command prompt window that might be active. It is not at all clear from your question what it is you hope to achieve. – Peter Duniho Jul 18 '17 at 22:20

2 Answers2

1

To set the working directory, you can also do it using the ProcessStartInfo like this:

using System;
using System.Diagnostics;

namespace so45176273
{
    internal class Program
    {
        private static void Main(string[] args)
        {
            var startInfo = new ProcessStartInfo("cmd")
            {
                WorkingDirectory = @"c:\Trash",
                Arguments = "/k" // will leave the process running until you type exit
            };

            Process.Start(startInfo);

            Console.WriteLine("Press any key to continue...");
            Console.ReadKey();
        }
    }
}
Black Frog
  • 11,595
  • 1
  • 35
  • 66
0

I believe this is the answer you are looking for.

Process.Start("cmd", @"/c cd C:\Users\user1\Desktop");
Black Frog
  • 11,595
  • 1
  • 35
  • 66
Rostech
  • 322
  • 1
  • 11