Issue WSL commands and read returned value from C#

  .net-core, c++, cmd, windows, windows-subsystem-for-linux

I am writing a code to execute some commands against wsl, parsing and reading the returned value is important.

Project is a .net core console app 3.1

wsl2 is enabled on the system

for example, listing all the available wsl images on my local machine i am using a snippet found in an answer provided in another "kind of related" SO post.

using (var proc = new Process
            {
                StartInfo = new ProcessStartInfo
                {
                    FileName = @"cmd.exe",
                    UseShellExecute = false,
                    RedirectStandardOutput = true,
                    RedirectStandardInput = true,
                    CreateNoWindow = true,
                }
            })
            {
                proc.Start();
                proc.StandardInput.WriteLine("wsl --list");
                System.Threading.Thread.Sleep(500);
                proc.StandardInput.Flush();
                proc.StandardInput.Close();
                proc.WaitForExit(5000);
                var c = proc.StandardOutput.ReadToEnd();
                Console.WriteLine(c);
                Console.ReadLine();
            }

now the expected output should be

enter image description here

what i am getting is

enter image description here

if i inspect using breakpoint i get this in "var c"

enter image description here

Ideally i want to be able to have a list that contains the 2 dockers items inside C#, changing the wait time didn’t help.

Source: Windows Questions

LEAVE A COMMENT