我正在尝试使用Console应用程序使用Net Core 2.0自动化机器设置,我需要运行一些NVM命令来配置节点版本。
我正在尝试使用我需要的NVM命令运行一个.bat文件,但是我会收到以下错误:
此文件没有与其执行此操作的程序相关的程序。请安装程序,或者,如果已经安装了程序,请在默认程序控制面板中创建协会。
如果我直接从CMD执行.bat文件,则可以正常工作,但是当我的控制台应用程序运行时,我会收到此错误。
'file.bat'命令是:
nvm version
nvm install 6.11.4
nvm use 6.11.4
nvm list
npm --version
我的csharp函数运行命令:
public static int ExecuteCommand()
{
int exitCode;
ProcessStartInfo processInfo;
Process process;
processInfo = new ProcessStartInfo("cmd.exe", $"/C file.bat")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
process = Process.Start(processInfo);
process.OutputDataReceived += (s, e) =>
{
Console.ForegroundColor = ConsoleColor.DarkGray;
Console.WriteLine("cmd >" + e.Data);
Console.ResetColor();
};
process.BeginOutputReadLine();
process.ErrorDataReceived += (s, e) =>
{
Console.ForegroundColor = ConsoleColor.Red;
Console.WriteLine(e.Data);
Console.ResetColor();
};
process.BeginErrorReadLine();
process.WaitForExit();
exitCode = process.ExitCode;
Console.WriteLine("ExitCode: " + exitCode.ToString(), "ExecuteCommand");
process.Close();
return exitCode;
}
我的期望是让此工作,因为之后我需要运行其他几个命令,例如NPM安装,Gulp Install等。
对可能发生的事情有任何想法吗?
纯粹基于测试,如果您更改此部分:
processInfo = new ProcessStartInfo("cmd.exe", $"/C file.bat")
{
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
不使用构造函数参数,而是手动设置参数,例如:
processInfo = new ProcessStartInfo()
{
FileName = "cmd.exe",
Arguments = $"/C file.bat",
CreateNoWindow = true,
UseShellExecute = false,
RedirectStandardError = true,
RedirectStandardOutput = true
};
应该解决这个问题。不确定为什么,因为从github代码上processstartinfo上,构造函数仅收到参数并将其存储在各自的属性上(文件名和参数)。