从C#调用WSL bash.exe

Gee*_*_SO 6 c# windows-subsystem-for-linux

通常出于好奇,我编写了一个小应用程序,以使用Ubuntu / WSL和Xming窗口服务器在Windows上启动Terminator Shell。

从外壳手动执行操作,我可以在Windows上运行Firefox,gedit,Terminator等,这非常酷。

所以我检查了bash.exe使用位置where bash并返回了...

C:\Windows\System32\bash.exe
Run Code Online (Sandbox Code Playgroud)

但是,当我尝试运行此代码时...

using (var xminProc = new Process())
{
    xminProc.StartInfo.FileName = @"C:\Program Files (x86)\Xming\Xming.exe";
    xminProc.StartInfo.Arguments = ":0 -clipboard -multiwindow";
    xminProc.StartInfo.CreateNoWindow = true;
    xminProc.Start();
}
using (var bashProc = new Process())
{
    bashProc.StartInfo.FileName = @"C:\Windows\System32\bash.exe";
    bashProc.StartInfo.Arguments = "-c \"export DISPLAY=:0; terminator; \"";
    bashProc.StartInfo.CreateNoWindow = true;
    bashProc.Start();
}
Run Code Online (Sandbox Code Playgroud)

我得到了错误...

System.ComponentModel.Win32Exception: 'The system cannot find the file specified'
Run Code Online (Sandbox Code Playgroud)

检查我的整个系统是否bash.exe显示它确实完全在另一个地方...

bash.exe的位置

我不确定该位置是否是我可以依靠的位置,我担心它是短暂的,并且在Windows Store更新期间可能会更改,尽管我对此可能有误。

为什么命令提示符显示bash.exeSystem32但实际上完全在另一个位置?

我可以让C#也使用该System32位置吗?

Ton*_*Nam 6

正如 @Biswapriyo 所说,首先在您的解决方案上将 platafrom 设置为 x64:

在此输入图像描述

然后你可以在你的 ubuntu 机器上从 C# 运行:

            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();

            }
Run Code Online (Sandbox Code Playgroud)