C# “试图跑步时卡住”;cmd.exe/c SYSTEMINFO“;在C中#
我试图在我的C#WPF应用程序中运行以下代码。每当我使用dir之类的东西时(我可能应该提到输出是VisualStudio中我的工作文件夹的目录,而不是System32),它都允许这样做。但是,如果我使用systeminfo或将工作目录设置为C:\Windows\System32,它将挂起C# “试图跑步时卡住”;cmd.exe/c SYSTEMINFO“;在C中#,c#,.net,wpf,process,cmd,C#,.net,Wpf,Process,Cmd,我试图在我的C#WPF应用程序中运行以下代码。每当我使用dir之类的东西时(我可能应该提到输出是VisualStudio中我的工作文件夹的目录,而不是System32),它都允许这样做。但是,如果我使用systeminfo或将工作目录设置为C:\Windows\System32,它将挂起 MessageBox.Show("STARTED"); var processInfo = new ProcessStartInfo("cmd.exe", "/c system
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));
有什么想法吗?刚刚尝试过这个,效果如期。
当然,您需要在进程关闭之前读取重定向的输出
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());
尝试
ProcessStartInfo(“cmd.exe”,“c\”systeminfo\”)
如果将CreateNoWindow
设置为false(因此它会显示命令提示窗口)并运行它,会发生什么?它显示任何消息吗?@dr_andonuts没有工作:(您意识到,如果重定向输出,您必须读取输出,对吗?如果您不这样做,它将填充管道的缓冲区,并挂起试图打印某些内容的线程。@不,与更新的代码不同。您必须在等待进程退出之前读取它。如果您等待进程退出,而它打印的内容太多,则会导致错误。)I’我将挂起并且永远不会退出,而且您仍然不会读取输出来解除对它的挂起。为什么要启动p两次?