How to use PHP CLI in C#

2019-02-25 16:03发布

问题:

I'm from China,so my english maybe is really poor. I try my best to make you understand my question. I want to use PHP CLI in my C# project. I tried code like this

        Process p = new Process();
        p.StartInfo.FileName = "cmd.exe";
        p.StartInfo.Arguments = command;
        p.StartInfo.UseShellExecute = false;
        p.StartInfo.RedirectStandardInput = true;
        p.StartInfo.RedirectStandardOutput = true;
        p.StartInfo.RedirectStandardError = true;
        p.StartInfo.CreateNoWindow = true;
        try
        {
            p.Start();
            p.StandardInput.WriteLine(command);
            p.StandardInput.WriteLine("exit");
            p.WaitForExit(1000);
            StreamReader reader = new StreamReader(p.StandardOutput.BaseStream, Encoding.GetEncoding("utf-8"));
            string text= reader.ReadToEnd();
            if (text.IndexOf(command) != -1)
            {
                int start = text.IndexOf(command) + command.Length;
                string endstring = rootpath + ">exit";
                int end = text.IndexOf(endstring);
                text = text.Substring(start, text.Length - start - endstring.Length).Trim();

                return text;
            }
            return "";
        }
        catch (System.Exception ex)
        {
            return "";
        }
        finally
        {
            p.Close();
        }

As the returned string is not what I need, I use substring to get the Correct results, but sometimes I can't get what I want to in the truth. I think my method maybe is not correct,but I cant't find any information from the Internet.

Can you help me? Thank you very much! Looking forward to your reply

回答1:

If I go by your code example the question does not make sense. However according to your question you can execute a PHP script from the CLI and collect the output using something like the following:

System.Diagnostics.Process proc = new System.Diagnostics.Process();
string sOutput = "";

proc.EnableRaisingEvents = false;
proc.StartInfo.FileName = "php.exe";
proc.StartInfo.Arguments = "-f file.php";
proc.StartInfo.RedirectStandardOutput = true;

System.IO.StreamReader hOutput = proc.StandardOutput;

proc.WaitForExit(2000);

if(proc.HasExited)
   sOutput = hOutput.ReadToEnd();           

Half of this code is my own and the rest I derived from a snippet I found via Google.

Hopefully this is what you are looking for.