How to execute this command in cmd prompt using C#

Andreas ss 726 Reputation points
2020-12-18T20:13:34.533+00:00

Hello!

I am trying to execute a command in cmd.exe using C#.

Normally, I would open the cmd.exe prompt manually and I would go the the directory: "C:\myproject" which is the directory I need to first select.

Secondly, I would manually run the command: "node fileWithCommands.js" which is a ".js" file which exists in the "C:\myproject" directory. I would then VISUALLY see commands executing in the actual cmd window that is opened.

So now I am trying to emulate this above manual task by executing that using C#. But the cmd window is only opening with "C:\myproject" selected and the below command is not executing?

Thank you!

Code not executing?

p.StartInfo.Arguments = "node fileWithCommands.js";

Complete code:

            Process p = new Process();
            p.StartInfo.FileName = "C:\\Windows\\system32\\cmd.exe";
            p.StartInfo.WorkingDirectory = @"C:\myproject";
            p.StartInfo.Arguments = "node fileWithCommands.js";
            p.Start();
Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,820 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
10,193 questions
0 comments No comments
{count} votes

Accepted answer
  1. Karen Payne MVP 35,031 Reputation points
    2020-12-18T21:13:57.993+00:00

    @Andreas ss

    Try the following

    var p = new Process  
    {  
        StartInfo =  
        {  
            FileName = "node",   
            WorkingDirectory = @"C:\myproject",   
            Arguments = "fileWithCommands.js"  
        }  
    };  
    
    3 people found this answer helpful.

1 additional answer

Sort by: Most helpful
  1. RLWA32 40,011 Reputation points
    2020-12-18T21:16:24.127+00:00

    Try with

    p.StartInfo.Arguments = "/C node fileWithCommands.js";