How To: Execute command line in C#, get STD OUT results

后端 未结 17 1244
既然无缘
既然无缘 2020-11-21 13:12

How do I execute a command-line program from C# and get back the STD OUT results? Specifically, I want to execute DIFF on two files that are programmatically selected and wr

17条回答
  •  渐次进展
    2020-11-21 14:09

    Just for fun, here's my completed solution for getting PYTHON output - under a button click - with error reporting. Just add a button called "butPython" and a label called "llHello"...

        private void butPython(object sender, EventArgs e)
        {
            llHello.Text = "Calling Python...";
            this.Refresh();
            Tuple python = GoPython(@"C:\Users\BLAH\Desktop\Code\Python\BLAH.py");
            llHello.Text = python.Item1; // Show result.
            if (python.Item2.Length > 0) MessageBox.Show("Sorry, there was an error:" + Environment.NewLine + python.Item2);
        }
    
        public Tuple GoPython(string pythonFile, string moreArgs = "")
        {
            ProcessStartInfo PSI = new ProcessStartInfo();
            PSI.FileName = "py.exe";
            PSI.Arguments = string.Format("\"{0}\" {1}", pythonFile, moreArgs);
            PSI.CreateNoWindow = true;
            PSI.UseShellExecute = false;
            PSI.RedirectStandardError = true;
            PSI.RedirectStandardOutput = true;
            using (Process process = Process.Start(PSI))
                using (StreamReader reader = process.StandardOutput)
                {
                    string stderr = process.StandardError.ReadToEnd(); // Error(s)!!
                    string result = reader.ReadToEnd(); // What we want.
                    return new Tuple (result,stderr); 
                }
        }
    

提交回复
热议问题