How to use PHP CLI in C#

拈花ヽ惹草 提交于 2019-12-02 02:43:48

问题


I'm from China, so my english maybe is really poor. I will 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 really want. I think my method might not be correct,but I can't find any information on the Internet.


回答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.



来源:https://stackoverflow.com/questions/6408053/how-to-use-php-cli-in-c-sharp

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!