2

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.

2
  • 1
    Please format your question and wrap your code in code tags. Commented Jun 20, 2011 at 7:31
  • 3
    Please explain what the actual results are and expected results should be. Commented Jun 20, 2011 at 7:42

1 Answer 1

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.

Sign up to request clarification or add additional context in comments.

1 Comment

yes ,thanks your help very much,I have resolved this problem use the similar method with yours thank you

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.