首页 > 解决方案 > 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 等。

知道会发生什么吗?

标签: c#automation.net-coredevopsnvm

解决方案


纯粹基于测试,如果您更改此部分:

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 代码构造函数仅接收参数并将它们存储在各自的属性(文件名和参数)中。


推荐阅读