0

I had this code snippet taken from Starting a process synchronously, and "streaming" the output :

type ProcessResult = { exitCode : int; stdout : string; stderr : string }

let executeProcess (exe,cmdline) =
    let psi = new System.Diagnostics.ProcessStartInfo(exe,cmdline) 
    psi.UseShellExecute <- false
    psi.RedirectStandardOutput <- true
    psi.RedirectStandardError <- true
    psi.CreateNoWindow <- true       
    psi.WorkingDirectory <- "C:\\GIT\\ProjectX" 
    let p = System.Diagnostics.Process.Start(psi) 
    let output = new System.Text.StringBuilder()
    let error = new System.Text.StringBuilder()
    p.OutputDataReceived.Add(fun args -> output.Append(args.Data) |> ignore)
    p.ErrorDataReceived.Add(fun args -> error.Append(args.Data) |> ignore)
    p.BeginErrorReadLine()
    p.BeginOutputReadLine()
    p.WaitForExit()
    { exitCode = p.ExitCode; stdout = output.ToString(); stderr = error.ToString() }

It is known that the result of the execution returns one or more lines in linux-like format (lines are separated by \n)

Nevertheless, executing the following code prints -1, so the \n had been removed.

let p = executeProcess ("git","branch -vv")
printfn "%d" (p.stdout.IndexOf('\n'))

This code in c# -which should be equivalent to the f# listed above- works nice:

    private static string[] RetrieveOrphanedBranches(string directory)
    {
        StringBuilder outputStringBuilder = new StringBuilder();
        ProcessStartInfo startInfo = new ProcessStartInfo();
        Process p = new Process();

        startInfo.CreateNoWindow = true;
        startInfo.RedirectStandardOutput = true;
        startInfo.RedirectStandardInput = true;
        startInfo.WorkingDirectory = directory;
        startInfo.UseShellExecute = false;
        startInfo.Arguments = "branch -vv";
        startInfo.FileName = "git";
        p.StartInfo = startInfo;
        p.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);
        p.Start();
        p.BeginOutputReadLine();

        p.WaitForExit();

        var l = outputStringBuilder.ToString().Split(new char[] { '\n' });
        return l;
    }

Is there a way to prevent f# removing new-line characters from process output?

Yván Ecarri
  • 1,661
  • 18
  • 39

1 Answers1

4

"equivalent" here is used quite freely.

C# code

p.OutputDataReceived += (sender, eventArgs) => outputStringBuilder.AppendLine(eventArgs.Data);

F# code:

p.OutputDataReceived.Add(fun args -> output.Append(args.Data) |> ignore)

So in C# code line (with \n) is added to the output. In F# it is added without \n. Use AppendLine in both.

Alex Netkachov
  • 13,172
  • 6
  • 53
  • 85