Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Run npm init from the c# console app

I have try to run "npm init" command from the c# console app, using this code:

private void Execute(string command, string arg)
    {
        Process p = new Process();
        p.StartInfo.FileName = command;
        p.StartInfo.Arguments = arg;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.WorkingDirectory = @"E:\Work\";  
        p.Start();
        p.WaitForExit();
    }

    Execute(@"C:\Program Files\nodejs\npm.cmd", "init");

But nothing happening. I getting only 2 empty lines after the running my app. Please, help to resolve this problem.

like image 565
Nisu Avatar asked May 12 '16 17:05

Nisu


3 Answers

Take a look at my example of running the npm run dist command.

var psiNpmRunDist = new ProcessStartInfo
{
    FileName = "cmd",
    RedirectStandardInput = true,
    WorkingDirectory = guiProjectDirectory
};
var pNpmRunDist = Process.Start(psiNpmRunDist);
pNpmRunDist.StandardInput.WriteLine("npm run dist & exit");
pNpmRunDist.WaitForExit();
like image 113
nopara73 Avatar answered Sep 19 '22 11:09

nopara73


The following works for me:

private static string RunCommand(string commandToRun, string workingDirectory = null)
{
    if (string.IsNullOrEmpty(workingDirectory))
    {
        workingDirectory = Directory.GetDirectoryRoot(Directory.GetCurrentDirectory());
    }

    var processStartInfo = new ProcessStartInfo()
    {
        FileName = "cmd",
        RedirectStandardOutput = true,
        RedirectStandardInput = true,
        WorkingDirectory = workingDirectory
    };

    var process = Process.Start(processStartInfo);

    if (process == null)
    {
        throw new Exception("Process should not be null.");
    }

    process.StandardInput.WriteLine($"{commandToRun} & exit");
    process.WaitForExit();

    var output = process.StandardOutput.ReadToEnd();
    return output;
}

You would use this like so:

var initResult = RunCommand("npm run init", @"E:\Work\");

This works for dotnet core as well as the standard .net framework.

like image 40
JMK Avatar answered Sep 16 '22 11:09

JMK


I have resolved this problem like this:

foreach (string s in commands)
{
   proc = Process.Start("npm.cmd", s);
   proc.WaitForExit();
}
like image 40
Nisu Avatar answered Sep 18 '22 11:09

Nisu