Search code examples
c#.netregistrycapture

How to capture Shell command output in C#?


Summary:

  • query registry on remote machine
  • capture output to use in application
  • needs to be in csharp
  • so far all methods used can only query on the local machine
  • any hope is greatly appreciated

Full issue:

I need to find a way to run a commandline command in csharp and capture its output. I know how to do this in Perl, below is the code I would use in Perl.

#machine to check
my $pc = $_[0];
#create location of registry query
my $machine = "\\\\".$pc."\\HKEY_USERS";
#run registry query
my @regQuery= `REG QUERY $machine`;

Any suggestions on how to do this in csharp would be welcome. So far ive tried using the RegistryKey OurKey = Registry.Users method and it works great but i can not query the registry on a remote machine.

Please let me know if you need any more information.

SOLUTION:(Thank you to @Robaticus)

private void reg(string host)
        {

            string build = "QUERY \\\\" + host + "\\HKEY_USERS";
            string parms = @build;
            string output = "";
            string error = string.Empty;

            ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms);

            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            psi.UseShellExecute = false;
            System.Diagnostics.Process reg;
            reg = System.Diagnostics.Process.Start(psi);
            using (System.IO.StreamReader myOutput = reg.StandardOutput)
            {
                output = myOutput.ReadToEnd();
            }
            using (System.IO.StreamReader myError = reg.StandardError)
            {
                error = myError.ReadToEnd();

            }
            Output.AppendText(output + "\n");


        }  

Solution

  • You might have to tweak this a bit, but here's some (slightly modified from the original) code that redirects stdout and stderr for a process:

            string parms = @"QUERY \\machine\HKEY_USERS";
            string output = "";
            string error = string.Empty;
    
            ProcessStartInfo psi = new ProcessStartInfo("reg.exe", parms);
    
            psi.RedirectStandardOutput = true;
            psi.RedirectStandardError = true;
            psi.WindowStyle = System.Diagnostics.ProcessWindowStyle.Normal;
            psi.UseShellExecute = false;
            System.Diagnostics.Process reg;
            reg = System.Diagnostics.Process.Start(psi);
            using (System.IO.StreamReader myOutput = reg.StandardOutput)
            {
                output = myOutput.ReadToEnd();
            }
            using(System.IO.StreamReader myError = reg.StandardError)
            {
                error = myError.ReadToEnd();
    
            }