c# - ProcessStartInfo 启动“cmd.exe”运行“nvm”命令安装节点版本弹出程序关联错误
问题描述
我正在尝试使用带有控制台应用程序的 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 install、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
};
应该做的伎俩。不知道为什么,因为从 ProcessStartInfo 上的 github 代码构造函数仅接收参数并将它们存储在各自的属性(文件名和参数)中。
推荐阅读
- php - 在虚拟主机上运行的 PHP 不会为图像创建目录
- postgresql - 在 PostgreSQL 中如何操作多个子查询执行顺序?
- javascript - Javascript 输入监听器
- python - 制作分层(MultiIndex)或从每个日期具有许多行的数据中进行透视
- android - 使用 ssp 和 sdp 库显示更大的 UI 组件大小
- javascript - 使用 JSP 的动态下拉值 onChange
- c# - 从 DataTable 在 WPF 中的数据网格中显示图像
- reactjs - 在 React 中的按钮上添加和删除类
- ios - iOS中的React Native RefreshControl下拉时显示一条白线
- unity3d - 统一更改脚本附加到的所有对象的公共变量