C#执行cmd命令不起作用

时间:2013-05-11 15:56:55

标签: c# .net wpf

有人可以建议为什么下面的代码没有返回系统日期?

 ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "net time \\192.168.221.1");
            cmdInfo.CreateNoWindow = true;
            cmdInfo.RedirectStandardOutput = true;
            cmdInfo.RedirectStandardError = true;
            cmdInfo.UseShellExecute = false;

            Process cmd = new Process();
            cmd.StartInfo = cmdInfo;
            var output = new StringBuilder();
            var error = new StringBuilder();

            cmd.OutputDataReceived += (o, e) => output.Append(e.Data);
            cmd.ErrorDataReceived += (o, e) => error.Append(e.Data);

            cmd.Start();
            cmd.BeginOutputReadLine();
            cmd.BeginErrorReadLine();
            cmd.WaitForExit();
            cmd.Close();
            var s = output;
            var d = error;

输出

{Microsoft Windows [Version 6.1.7601]Copyright (c) 2009 Microsoft Corporation.  All rights reserved.D:\TEST\TEST\bin\Debug>}

1 个答案:

答案 0 :(得分:5)

试试这个

ProcessStartInfo cmdInfo = new ProcessStartInfo("cmd.exe", "/C net time \\\\192.168.221.1");

您需要添加/ C开关来捕获CMD shell中运行命令的输出 反斜杠也应加倍或使用字符串Verbatim前缀@