0

i have been looking up "how to get standard output from cmd" and i found a few tutorials, but none, yes NONE seemed to work, im trying to read all the output that "cmd.exe" has for me.

heres the whole code, Scroll down for the error location

    public static string C(string arguments, bool b)
    {
        System.Diagnostics.Process process = new 
        System.Diagnostics.Process();
        System.Diagnostics.ProcessStartInfo startInfo = new 
        System.Diagnostics.ProcessStartInfo();
        startInfo.WindowStyle = 
        System.Diagnostics.ProcessWindowStyle.Hidden;
        process.StartInfo.RedirectStandardOutput = true;
        process.StartInfo.RedirectStandardInput = true;
        process.StartInfo.UseShellExecute = false;
        startInfo.FileName = "cmd.exe";
        startInfo.Arguments = arguments;
        process.StartInfo = startInfo;
        process.Start();

        string res = "";
        if (b)
        {
            StringBuilder q = new StringBuilder();
            while (!process.HasExited)
            {
                q.Append(process.StandardOutput.ReadToEnd());
            }
            string r = q.ToString();
            res = r;
        }
        if(res == "" || res == null)
        {
            return "NO-RESULT";
        }
        return res;

    }

Where i get my error (System.InvalidOperationException: 'StandardOut has not been redirected or the process hasn't started yet.')

   string res = "";
   StringBuilder q = new StringBuilder();
   while (!process.HasExited)
   {
       q.Append(process.StandardOutput.ReadToEnd()); // Right here
   }
   string r = q.ToString();
   res = r;

1 Answers1

0

You are creating a ProcessStartInfo named startInfo, then set some properties on process.StartInfo and then assign startInfo to process.StartInfo basically reverting what you set previously.

You should be setting RedirectStandardOutput, RedirectStandardInput and UseShellExecute on the startInfo:

System.Diagnostics.Process process = new System.Diagnostics.Process();
System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
startInfo.RedirectStandardOutput = true;
startInfo.RedirectStandardInput = true;
startInfo.UseShellExecute = false;
startInfo.FileName = "cmd.exe";
startInfo.Arguments = arguments;
process.StartInfo = startInfo;
process.Start();
Szabolcs Dézsi
  • 8,743
  • 21
  • 29