paul deter
paul deter

Reputation: 857

how to read output of a command run using cmd.exe

I would like to programatically run following command on command prompt, read its output and then just kill the command window.

sc query eventlog

When I run this command manually, below is what I get.

enter image description here

Here is code what I have for it.

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;
        }

However in my case, the it just keep waiting on call for WaitForExit. For that I might have to kill this process. But I see following in the ouput varaible.

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

What am I doing wrong here?

Upvotes: 3

Views: 1748

Answers (1)

Mark PM
Mark PM

Reputation: 2919

You need to call sc.exe instead of cmd.exe:

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

Upvotes: 4

Related Questions