【问题标题】:How to use PHP CLI in C#如何在 C# 中使用 PHP CLI
【发布时间】:2011-06-20 07:30:00
【问题描述】:

我来自中国,所以我的英语可能真的很差。我会尽力让你理解我的问题。 我想在我的 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 来获得正确的结果,但有时我无法获得我真正想要的结果。 我想我的方法可能不正确,但是我在网上找不到任何资料。

【问题讨论】:

  • 请格式化您的问题并将您的代码包装在代码标签中。
  • 请说明实际结果和预期结果。

标签: c# php .net command-line-interface


【解决方案1】:

如果我通过您的代码示例,这个问题没有意义。但是,根据您的问题,您可以从 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 找到的snippet

希望这是您正在寻找的。

【讨论】:

  • 是的,非常感谢你的帮助,我已经用你的类似方法解决了这个问题,谢谢
猜你喜欢
  • 1970-01-01
  • 2023-02-13
  • 2015-02-04
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多