C# 用按钮执行 CMD.exe 中的命令

C# Execute a command in CMD.exe with a button

我曾经有一个我在 VB.net 中创建的小工具到 enable/disable 我的以太网。

现在我正尝试在 C# 中重新创建它,但我似乎无法弄清楚如何让命令工作。

下面报错,可能是我对C#一窍不通

private void btnDisabled_Click(object sender, EventArgs e)
{
    Process.Start("CMD", "netsh interface set interface "Ethernet" DISABLED");
}

应该在命令提示符中输入 netsh interface set interface "Ethernet" DISABLED。

我显然把整个代码都错了,但我不知道应该怎么做。

有人有什么建议吗?

谢谢

你可以测试这个。

启用

static void Enable(string interfaceName)
{
 System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", String.Format("interface set interface {0} enable", interfaceName ));
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}

禁用

static void Disable(string interfaceName)
{
    System.Diagnostics.ProcessStartInfo psi =
        new System.Diagnostics.ProcessStartInfo("netsh", String.Format("interface set interface {0} disable", interfaceName ));
    System.Diagnostics.Process p = new System.Diagnostics.Process();
    p.StartInfo = psi;
    p.Start();
}

在一种方法中。

    static void SetInterface(string interfaceName, bool enable)
    {
        string type;
        if (enable == true) type = "enable";
        else type = "disable";

        System.Diagnostics.ProcessStartInfo psi =
            new System.Diagnostics.ProcessStartInfo("netsh", String.Format("interface set interface {0} {1}", interfaceName, type));
        System.Diagnostics.Process p = new System.Diagnostics.Process();
        p.StartInfo = psi;
        p.Start();
    }

我觉得下面的回答应该有帮助Why does Process.Start("cmd.exe", process); not work?. You may also need to execute the process with admin rights (see How to start a Process as administrator mode in C#)

你没有包含它正在输出的错误,但是从上面的阅读来看,你似乎在把 "Ethernet" 转义你的字符串并且它试图访问以太网对象而不是发送到命令线。如果要在字符串中传递引号,可以用 \" 代替 "。