[英]C# Execute a command in CMD.exe with a button
我曾經有一個在VB.net中創建的小工具來啟用/禁用我的以太網。
現在,我正在嘗試在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();
}
我認為以下答案應有助於為什么Process.Start(“ cmd.exe”,process); 不行? 。 您可能還需要以管理員權限執行流程(請參閱如何在C#中以管理員身份啟動流程 )
您沒有包括它輸出的錯誤,但是通過閱讀上面的內容,您似乎在將“以太網”轉義為字符串,並試圖訪問以太網對象而不是發送至命令行。 如果要在字符串中傳遞引號,則可以使用\\“代替”。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.