如何在C#中使用PHP CLI

我来自中国,所以我的英语可能真的很差。 我尽力让你理解我的问题。 我想在我的C#项目中使用PHP CLI。 我试过像这样的代码

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(); } 

由于返回的字符串不是我需要的,我使用substring来获得正确的结果,但有时我无法得到我想要的真相。 我认为我的方法可能不正确,但我无法从互联网上找到任何信息。

你能帮助我吗? 非常感谢你! 期待你的回复

如果我按照您的代码示例进行操作,则问题没有意义。 但是根据您的问题,您可以从CLI执行PHP脚本并使用以下内容收集输出:

 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(); 

这段代码的一半是我自己的,其余的是从我通过Google找到的代码片段中获得的 。

希望这是你正在寻找的。