jeudi 10 décembre 2020

Failing to get output from System.Diagnostics.Process that is running a basic tasklist command

I am trying to use System.Diagnostics.Process to start something like a tasklist command that will run in the background and monitor things as an automated test case proceeds. At the end I would like to grab the output into a text file or string that I can query later. However, I don't seem to be getting anything in Standardoutput or StandardError and my efforts to write to a file have also failed. This is what I have so far.

process = Launch();
.
..
Do some stuff in the middle
..
.
Shutdown(process)


    public static Process Launch()
    {
        Process process = null;
        try
        {
            process = new Process();
            process.StartInfo.WorkingDirectory = @"C:\temp";
            process.StartInfo.FileName = "tasklist";
            process.StartInfo.Arguments = "/V /FO LIST";
            process.StartInfo.RedirectStandardOutput = true;
            process.StartInfo.RedirectStandardError = true;
            process.StartInfo.UseShellExecute = false;
            process.Start();

            return process;
        }
        catch (Exception e)
        {
            Assert.Fail(e.Message);
            return process;
        }
    }
    
    public static void Shutdown(Process process)
    {
        try
        {
            StreamReader myStreamError = process.StandardError;
            StreamReader myStreamOther = process.StandardOutput;

            Console.WriteLine(myStreamError.ReadLine());
            Console.WriteLine(myStreamOther.ReadLine());

            process.WaitForExit();

            process.Dispose();
        }
        catch (Exception e)
        {
            Assert.Fail(e.Message);
            return process;
        }
    }

So anything that would write to file or output to Console.WriteLine. Considering that after i launch the initial tasklist command the test will be doing other things from 3-5 minutes. So i would like to capture all that.

Aucun commentaire:

Enregistrer un commentaire