如何在C#中使用PHP CLI
本文关键字:PHP CLI | 更新日期: 2023-09-27 17:59:56
我来自中国,所以我的英语可能真的很差。我会尽力让你理解我的问题。我想在我的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();
}
由于返回的字符串不是我所需要的,我使用子字符串来获得正确的结果,但有时我无法获得我真正想要的结果。我想我的方法可能不正确,但我在网上找不到任何信息。
如果我以你的代码示例为例,这个问题就没有意义了。但是,根据您的问题,您可以从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();
这段代码有一半是我自己的,其余的是我通过谷歌找到的一个片段。
希望这就是你想要的。