Calling WSL bash.exe from C#

随声附和 提交于 2019-12-05 06:56:08

As @Biswapriyo stated first set the platafrom to x64 on your solution:

Then you may run on your ubuntu machine from c# as:

            Console.WriteLine("Enter command to execute on your Ubuntu GNU/Linux");
            var commandToExecute = Console.ReadLine();

            // if command is null use 'ifconfig' for demo purposes
            if (string.IsNullOrWhiteSpace(commandToExecute))
            {
                commandToExecute = "ifconfig";
            }


            // Execute wsl command:
            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 " + commandToExecute);
                System.Threading.Thread.Sleep(500); // give some time for command to execute
                proc.StandardInput.Flush();
                proc.StandardInput.Close();
                proc.WaitForExit(5000); // wait up to 5 seconds for command to execute
                Console.WriteLine(proc.StandardOutput.ReadToEnd());
                Console.ReadLine();

            }
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!