执行带参数的CMD不起作用

时间:2016-10-28 21:40:30

标签: c# cmd

我正在尝试执行此CMD命令来更改我的DNS,但它无法正常工作。我没有收到任何错误。它要求以管理员身份运行,但它不起作用。

如果我手动将参数输入CMD,它确实有效。

这是我的代码:

System.Diagnostics.ProcessStartInfo myProcessInfo = new System.Diagnostics.ProcessStartInfo(); 
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") + @"\System32\cmd.exe";
myProcessInfo.Arguments = "set DNS1=198.168.97.1 " +
    "set DNS2=5.2.2.2 " +
    "set DNS3=206.19.29.17 " +
    "set INTERFACE=Ethernet " +
    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no " +
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 " +
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3" +
    "ipconfig /flushdns";

myProcessInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden; 
myProcessInfo.Verb = "runas"; 
System.Diagnostics.Process.Start(myProcessInfo);

2 个答案:

答案 0 :(得分:1)

实际上你正在做的是将所有命令作为普通参数附加。为每个命令运行命令行,或在命令之间添加&符号以链接它们。此外,您需要使用/c - 参数来传递命令。所以你的代码看起来像这样:

myProcessInfo.Arguments = "/c 'set DNS1=198.168.97.1 && " +
                                    "set DNS2=5.2.2.2 && " +
                                    "set DNS3=206.19.29.17 && " +
                                    "set INTERFACE=Ethernet && " +
                                    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no && " +
                                    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 && " +
                                    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3 && " +
                                    "ipconfig /flushdns'";

答案 1 :(得分:0)

也许是这样的:

var tempFileName = Path.GetTempFileName() + ".cmd";
File.WriteAllLines(tempFileName, new[]
{
    "set DNS1=198.168.97.1 ", 
    "set DNS2=5.2.2.2 ",
    "set DNS3=206.19.29.17 ",
    "set INTERFACE=Ethernet ",
    "netsh int ipv4 set dns name='%INTERFACE%' static %DNS1% primary validate=no ",
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS2% index=2 ",
    "netsh int ipv4 add dns name='%INTERFACE%' %DNS3% index=3",
    "ipconfig /flushdns"
});

var myProcessInfo = new ProcessStartInfo();
myProcessInfo.FileName = Environment.ExpandEnvironmentVariables("%SystemRoot%") 
    + @"\System32\cmd.exe /C " + tempFileName;
myProcessInfo.WindowStyle = ProcessWindowStyle.Hidden;
myProcessInfo.Verb = "runas";
var myProcess = Process.Start(myProcessInfo);
if (myProcess != null)
    while (!myProcess.HasExited)
    {
        myProcess.Refresh();
        Thread.Sleep(TimeSpan.FromSeconds(1));
    }
File.Delete(tempFileName);