How to capture Shell command output in C#?

后端 未结 5 450
梦毁少年i
梦毁少年i 2020-12-05 05:30

Summary:

  • query registry on remote machine
  • capture output to use in application
  • needs to be in csharp
  • so far all methods used can onl
5条回答
  •  夕颜
    夕颜 (楼主)
    2020-12-05 06:14

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

提交回复
热议问题