简体   繁体   English

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

[英]C# Execute a command in CMD.exe with a button

I used to have a small tool i created in VB.net to enable/disable my Ethernet. 我曾经有一个在VB.net中创建的小工具来启用/禁用我的以太网。

Right now i am trying to recreate it in C# but i cannot seem to figure out how to get the command to work. 现在,我正在尝试在C#中重新创建它,但似乎无法弄清楚如何使命令起作用。

The following gives a error, probably because i am clueless with C#. 以下给出了一个错误,可能是因为我对C#一无所知。

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

Which is supposed to enter netsh interface set interface "Ethernet" DISABLED in command prompt. 应该在命令提示符下输入netsh interface set interface“ Ethernet” DISABLED。

I clearly have the entire code wrong, but i cant find out how it should be. 我显然整个代码都错了,但是我找不到应该怎么做。

Anybody got any advice? 有人有任何建议吗?

Thanks 谢谢

You can test this one. 您可以对此进行测试。

ENABLE 启用

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();
}

DISABLE 禁用

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();
}

In one Method. 在一种方法中。

    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();
    }

I think the following answer should help Why does Process.Start("cmd.exe", process); 我认为以下答案应有助于为什么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# ) 您可能还需要以管理员权限执行流程(请参阅如何在C#中以管理员身份启动流程

You didn't include the error it's outputting, but from reading the above, it looks like you're putting "Ethernet" is escaping your string and it's attempting to access the Ethernet object rather sending to the command line. 您没有包括它输出的错误,但是通过阅读上面的内容,您似乎在将“以太网”转义为字符串,并试图访问以太网对象而不是发送至命令行。 If you want to pass a quote mark in a string, you can put \\" instead of ". 如果要在字符串中传递引号,则可以使用\\“代替”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM