此代码在我的测试系统上运行正常(原始Windows-Server 2008 R2的副本)
private string _getNetFiles() { // prepare execution process ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c openfiles /query /Fo list"); processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardError = true; processStartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(437); processStartInfo.RedirectStandardOutput = true; // execute Process process = Process.Start(processStartInfo); process.WaitForExit(); // read outputs string stdOutput = process.StandardOutput.ReadToEnd(); string stdError = process.StandardError.ReadToEnd(); return stdOutput; }在原始系统上:我在Task-Manger中看到“cmd.exe / c openfiles / query / Fo list”任务,但此任务永远不会结束(process.WaitForExit()进程永远不会结束)。 原始系统上的Cmd: openfiles / query / fo list工作也没问题!
问题出在哪里?
关于raiserle
编辑:我可以使用任务管理器停止该过程。 stdOutput是正确的。 为什么不结束cmd-taks。
this code works fine on my test-system (Copy of the original Windows-Server 2008 R2)
private string _getNetFiles() { // prepare execution process ProcessStartInfo processStartInfo = new ProcessStartInfo("cmd.exe", "/c openfiles /query /Fo list"); processStartInfo.CreateNoWindow = true; processStartInfo.UseShellExecute = false; processStartInfo.RedirectStandardError = true; processStartInfo.StandardOutputEncoding = System.Text.Encoding.GetEncoding(437); processStartInfo.RedirectStandardOutput = true; // execute Process process = Process.Start(processStartInfo); process.WaitForExit(); // read outputs string stdOutput = process.StandardOutput.ReadToEnd(); string stdError = process.StandardError.ReadToEnd(); return stdOutput; }On the original system: I see the "cmd.exe /c openfiles /query /Fo list" task in the Task-Manger, but this task never end (process.WaitForExit() process never end ). Cmd on the original system: openfiles /query /fo list works also fine!
Where can the problem be?
regards raiserle
edit: I can stop the process with task-manager. The stdOutput is correct. Why don't end the cmd-taks.
最满意答案
子进程要么等待输入,要么读取其输出。 管道缓冲区不是无限大。 您需要不断地排除标准输出和标准错误。
从Process StandardOutput获取值看起来合理。 https://stackoverflow.com/a/24084220/122718文档如何安全地读取两个流。
另请注意cmd的Visual Basic Capture输出以及Hans Passant在此主题中所说的所有内容 。
使用没有输出重定向的Process类非常棘手且文档很少。
The child process is either waiting for input or for its output to be read. The pipe buffers are not infinitely big. You need to constantly drain both standard output as well as standard error.
Get Values from Process StandardOutput looks reasonable. https://stackoverflow.com/a/24084220/122718 documents how to safely read both streams.
Also note Visual Basic Capture output of cmd as well as everything that Hans Passant says on this topic.
Using the Process class without output redirection is quite tricky and poorly documented.
更多推荐
发布评论