-2

I am trying to get the output of the process line by line, but I am getting null value being returned. Can you please check my below code and let me know what wrong am doing here? Please suggest

Process process = new Process();
process.StartInfo.FileName = dirPath + "\\test.exe";
process.StartInfo.Arguments = "-a -h -s " + dir;
process.StartInfo.RedirectStandardOutput = true;
process.StartInfo.UseShellExecute = false;
process.StartInfo.CreateNoWindow = true;
process.Start();

using (StreamReader streamReader = Process.StandardOutput)
{
    string line = streamReader.ReadLine();
    while (line != null)
    {
        Console.WriteLine(line);
    }
}
process.WaitForExit();

If I use string line = streamReader.ReadToEnd() it displays all the lines.

FCin
  • 3,804
  • 4
  • 20
  • 49
Dhillli4u
  • 117
  • 12

1 Answers1

0

I was able to fix this by making the below changes. I needed to add !streamReader.EndOfStream in the while loop and then parse through each line by line by using streamReader.ReadLine() which worked for me.

                Process process = new Process();
                process.StartInfo.FileName = Pathdir + "\\test.exe";
                process.StartInfo.Arguments = "-a -h -s " + dir;
                process.StartInfo.RedirectStandardOutput = true;
                process.StartInfo.UseShellExecute = false;
                process.StartInfo.CreateNoWindow = true;
                process.Start();

                using (StreamReader streamReader = process.StandardOutput)
                {
                    while (!streamReader.EndOfStream)
                    {
                        string line = streamReader.ReadLine();
                        Console.WriteLine(line);
                    }
                }
Dhillli4u
  • 117
  • 12
  • If you want to make a suitable answer, explain what you did, just dont paste lumps of code, explain why it is you think it works, add any documentation that backs this up – TheGeneral Dec 11 '18 at 03:27
  • @TheGeneral I am trying to learn the coding side and am still in the starting stage. So my current method is based on trial and error method and the inputs you provide. If I am able to explain definitely I will add my points to the data in the future. – Dhillli4u Dec 11 '18 at 06:11