0

I execute JS file with cmd command in c# and i want when it stop the cmd is useless and exit automatically. It's possible to do it without a batch file?

    public static void ExecuteCommand(string command)
    {
        System.Diagnostics.Process process = new System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = command;
        process.StartInfo = startInfo;
        process.Start();
    }
  • What are the arguments? Calling cmd.exe without specifying /K or /C will terminate immediately – Steve Jun 19 '22 at 08:29
  • Cmd command: "node path\file.js" (js file auto close when the task is finished) – SplatStereer Jun 19 '22 at 08:31
  • Type cmd.exe ? on an existing command window. You will notice two parameters /K or /C. You need to add one of them to your arguments of ProcessStartInfo. A duplicate should exist here somewhere. – Steve Jun 19 '22 at 08:33
  • To wait for a newly created process, you can use `Process.WaitForExit` (with a timeout or without). – wohlstad Jun 19 '22 at 08:33
  • What do you mean wohlstad? – SplatStereer Jun 19 '22 at 08:36
  • _startInfo.Arguments = "/C " + command;_ The /C ask the cmd.exe to execute the comand and exit only at the command completion. – Steve Jun 19 '22 at 08:37
  • Your question's title is "How to wait ...". If you need your code to wait for the process to end after you start it with `process.Start`, you can use `Process.WaitForExit`: https://learn.microsoft.com/en-us/dotnet/api/system.diagnostics.process.waitforexit?view=net-6.0. I might have misunderstood what you need. – wohlstad Jun 19 '22 at 08:38
  • @wohlstad I think they want to wait on cmd.exe completing the task. Not really interested in stopping the current program. Yes, it is prone to misunderstandings. However I found a suitable duplicate now – Steve Jun 19 '22 at 08:39

0 Answers0