2

i want to get the result of a php file with Process.Start, my code:

public string RunPHP(string filename)
    {
        var p = new Process
        {
            StartInfo = new ProcessStartInfo("php", "-f \"" + filename + "\"")
            {
                RedirectStandardOutput = true,
                RedirectStandardError = true,
                UseShellExecute = false,
                CreateNoWindow = true
            }
        };
        Console.WriteLine("'" + p.StartInfo.Arguments + "'");
        var output = new StringWriter();
        var error = new StringWriter();

        p.OutputDataReceived += (sender, args) => { output.WriteLine(args.Data); Console.WriteLine(args.Data);  };
        p.ErrorDataReceived += (sender, args) => error.WriteLine(args.Data);
        p.Start();

        p.BeginOutputReadLine();
        p.BeginErrorReadLine();

        p.WaitForExit();

        if (p.ExitCode != 0)
        {
            throw new Exception(string.Format(
                "PHP failed with the following output:{0}{1}",
                /* {0} */ Environment.NewLine,
                /* {1} */ error.GetStringBuilder().ToString()));
        }
        var res = output.GetStringBuilder().ToString();
        return res;
    }

but i get the result only, if i'm press enter in the console application window. (php 7)

how can i avoid this?

yuisd8912
  • 21
  • 1
  • This is not a duplicate of the marked answer. In the linked "duplicate", that OP used synchronous `ReadToEnd` which causes the bug (I mean, causes the expected behavior of a dead lock). In fact this post is already using the accepted answer to that question by using the asynchronous reads. But I have no idea how to ask to "un close" this question.. – Quantic Jul 12 '16 at 22:16
  • I tried running your code and it works fine for me with the php .zip file from [here](http://windows.php.net/download/). I see you are pointing `StartInfo` to `"php"`, what does that resolve to for you? On my system I had to point to my extracted zip folder slash `php.exe`, `StartInfo = new ProcessStartInfo(@"C:\Users\me\Downloads\php-7.0.8-nts-Win32-VC14-x86\php.exe", "-f \"" + filename + "\"")` – Quantic Jul 12 '16 at 22:33

0 Answers0