c# - 如何读取使用 cmd.exe 运行的命令的输出

标签 c# .net-4.0

我想在命令提示符下以编程方式运行以下命令,读取其输出,然后终止命令窗口。

sc query eventlog

当我手动运行这个命令时,下面是我得到的结果。

enter image description here

这是我的代码。

class Program
    {
        static string output;
        static void Main(string[] args)
        {
            Process p = new Process();
            p.StartInfo.UseShellExecute = false;
            p.StartInfo.RedirectStandardOutput = true;
            p.StartInfo.FileName = "cmd.exe";
            p.StartInfo.Arguments = "sc query eventlog";
            p.OutputDataReceived += p_OutputDataReceived;
            p.Start();


            p.BeginOutputReadLine();

            p.WaitForExit();
            p.Kill();
        }

        static void p_OutputDataReceived(object sender, DataReceivedEventArgs e)
        {
            output += e.Data + Environment.NewLine;
        }

但是在我的例子中,它只是继续等待 WaitForExit 的调用。为此,我可能不得不终止这个过程。但是我在输出变量中看到了以下内容。

Microsoft Windows [Version 6.3.9600] (c) 2013 Microsoft Corporation. All rights reserved.

我在这里做错了什么?

最佳答案

您需要调用 sc.exe 而不是 cmd.exe:

p.StartInfo.FileName = "sc.exe";
p.StartInfo.Arguments = "query eventlog";

关于c# - 如何读取使用 cmd.exe 运行的命令的输出,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27950106/

相关文章:

c# - Automapper - 将字符串属性转换为 SelectList?

.net - clojure 与 C# 语言

c# - 使用 BlockingCollection<T> 作为单一生产者、单一消费者 FIFO 查询是否好?

c# - 在 C# 中以编程方式执行 gacutil 操作?

c# - 需要帮助找到一年中的第二个星期三

c# - 使 Entity Framework 实现一个接口(interface)

c# - 无法对 Pen 进行更改,因为权限无效

c# - 在连接之间共享事务

c# - 从 C# 编译 Silverlight 解决方案失败,出现错误 "The Silverlight 4 SDK is not installed"

c# - IEnumerable 的可能多重枚举?