C#启动NetSH命令行

C#启动NetSH命令行

问题描述:

对于我的学校项目,我想通过使用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垃圾回收器处置) –

首先,你应该重写的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