试图运行" cmd.exe / c SYSTEMINFO"在C#中

时间:2014-08-19 16:36:56

标签: c# .net wpf process cmd

我试图在我的C#WPF应用程序中运行以下代码。每当我使用像dir这样的东西时(我应该提到输出是我在Visual Studio中的工作文件夹的目录,而不是System32),它允许它。但是,如果我使用systeminfo或将工作目录设置为C:\ Windows \ System32,它会挂起......

        MessageBox.Show("STARTED");

        var processInfo = new ProcessStartInfo("cmd.exe", "/c systeminfo") {
            CreateNoWindow = true,
            UseShellExecute = false,
            RedirectStandardError = true,
            RedirectStandardOutput = true,
            //WorkingDirectory = @"C:\Windows\System32\"
        };

        // *** Redirect the output ***
        Process process = Process.Start(processInfo);

        if (process == null) return false;
        process.WaitForExit();
        MessageBox.Show("Done");

        string output = process.StandardOutput.ReadToEnd().ToLower();
        string error = process.StandardError.ReadToEnd();
        int exitCode = process.ExitCode;
        MessageBox.Show(output);
        MessageBox.Show(error);
        MessageBox.Show(exitCode.ToString(CultureInfo.InvariantCulture));

有什么想法吗?

1 个答案:

答案 0 :(得分:2)

试过这个并按预期工作 当然,您需要在进程关闭之前读取重定向的输出。

var processInfo = new ProcessStartInfo("cmd.exe", "/c systeminfo") 
{
    CreateNoWindow = true,
    UseShellExecute = false,
    RedirectStandardError = true,
    RedirectStandardOutput = true,
    WorkingDirectory = @"C:\Windows\System32\"
};

StringBuilder sb = new StringBuilder();
Process p = Process.Start(processInfo);
p.OutputDataReceived += (sender, args) => sb.AppendLine(args.Data);
p.BeginOutputReadLine();
p.WaitForExit();
Console.WriteLine(sb.ToString());