简体   繁体   中英

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.

Right now i am trying to recreate it in C# but i cannot seem to figure out how to get the command to work.

The following gives a error, probably because i am clueless with 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.

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); not work? . You may also need to execute the process with admin rights (see How to start a Process as administrator mode in 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 ".

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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