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.
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();
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.
I have resolved this problem like this:
foreach (string s in commands)
{
proc = Process.Start("npm.cmd", s);
proc.WaitForExit();
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With