2017-09-26 169 views
-1

對於我的學校項目,我想通過使用C#的NetSH建立連接。 我用Google搜索出頭了,並用下面的代碼上來:C#啓動NetSH命令行

using System; 
using System.Collections.Generic; 
using System.Linq; 
using System.Text; 
using System.Threading.Tasks; 
using System.Windows.Forms; 
using System.Diagnostics; 

namespace Server_Smart_Road 
{ 
    class Connection 
    { 
     private string FileName { get; } 
     private string Command { get; set; } 
     private bool UseShellExecute { get; } 
     private bool RedirectStandardOutput { get; } 

     private bool CreateNoWindow { get; } 

     public Connection() 
     { 
      FileName = "netsh.exe"; 
      Command = "wlan set hostednetwork mode=allow ssid=SmartRoad key=smartroad123"; 
      UseShellExecute = false; 
      RedirectStandardOutput = true; 
      CreateNoWindow = true; 

     } 

     public void ChangeCommand(string command) 
     { 
      Command = command; 
     } 

     public void Run() 
     { 
      Process process = new Process(); 
      process.StartInfo.FileName = FileName; 
      process.StartInfo.Arguments = Command; 
      process.StartInfo.UseShellExecute = UseShellExecute; 
      process.StartInfo.RedirectStandardOutput = RedirectStandardOutput; 
      process.StartInfo.CreateNoWindow = CreateNoWindow; 
     } 
    } 
} 

現在,我第一次運行名爲「過程」的實例(的run())來配置的連接,然後我用同樣的方法等一個啓動命令具有相同名稱的新實例。

在窗體我提出這個類(連接)的新實例與此代碼:

 private void btn_startnetwork_Click(object sender, EventArgs e) 
    { 
     connection = new Connection(); 
     connection.Run(); 
     connection.ChangeCommand("wlan start hostednetwork"); 
     connection.Run(); 
    } 

的問題是:我沒有看到任何程序打開時 我按一下按鈕。我知道我說'CreateNoWindow'應該是真的,但即使我將它設置爲false,它也不會啓動netSH。因此,我不知道該計劃是否應該做什麼。

我正在爲另一個命令啓動一個新進程。該過程再次啓動netsh.exe。我不知道這是否正確。

+1

你的過程將不會開始。之後用CreateNoWindow添加process.Start();另請參閱:https://msdn.microsoft.com/de-de/library/e8zac0ca(v=vs.110).aspx –

+0

o該死的我很笨...謝謝@ ralf.w。我應該在每個命令之後處理它嗎? – Gigitex

+0

在Run()結束時你的進程就是歷史;-)(由.net垃圾回收器處置) –

回答

1

首先,你應該重寫的run():

public void Run(string cmd) 
    { 
     Process process = new Process(); 
     process.StartInfo.FileName = FileName; 
     process.StartInfo.Arguments = cmd; 
     process.StartInfo.UseShellExecute = UseShellExecute; 
     process.StartInfo.RedirectStandardOutput = RedirectStandardOutput; 
     process.StartInfo.CreateNoWindow = CreateNoWindow; 
     process.Start(); 
    } 

,並調用它像這樣:

connection = new Connection(); 
connection.Run("wlan set hostednetwork mode=allow ssid=SmartRoad key=smartroad123"); 

,甚至更短的(你的第二個電話):

new Connection().Run("wlan start hostednetwork"); 

與額外的構造器

public Connection(string fn) : this() 
{ 
    FileName = fn; 
} 

這看起來更漂亮:

new Connection("netsh.exe").Run("wlan set hostednetwork ... "); 
new Connection("netsh.exe").Run("wlan start hostednetwork"); 
+0

如果使用額外的構造函數。我的房產會發生什麼?它如何知道這些信息? – Gigitex

+1

部分*:這()*首先調用默認的構造函數。如果你想改變你的財產,你必須首先把你連接到一個變量(連接第一=新的連接(); first.xxx = ZZZ; first.Run();等) –

+0

所以對於最後一部分妳說我需要爲每個過程製作一個新實例? – Gigitex