【问题标题】:Calling WSL bash.exe from C#从 C# 调用 WSL bash.exe
【发布时间】:2023-03-13 15:26:01
【问题描述】:

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

从 shell 手动操作,我可以在 Windows 上运行 Firefox、gedit、Terminator 等,非常酷。

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

C:\Windows\System32\bash.exe

但是当我尝试运行这段代码时...

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

我得到了错误...

System.ComponentModel.Win32Exception: 'The system cannot find the file specified'

检查我的整个系统中的bash.exe 发现它确实在另一个地方...

我不确定这个位置是否是我可以依赖的位置,我担心它是短暂的,并且可能会在 Windows 应用商店更新期间发生变化,尽管我可能错了。

为什么命令提示符显示bash.exe 位于System32,但它实际上完全位于另一个位置?

我能否让 C# 也使用 System32 位置?

【问题讨论】:

  • 将灵魂平台设置为x64。并使用Environment.GetEnvironmentVariable 获取 System32 文件夹。
  • 32 位程序将被放在File system redirector 下,因此使用路径C:\Windows\System32 看不到真正的system32 文件夹

标签: c# windows-subsystem-for-linux


【解决方案1】:

正如@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();

            }

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-08-07
    • 1970-01-01
    • 2019-01-14
    • 1970-01-01
    • 2021-09-04
    • 1970-01-01
    • 2019-12-07
    相关资源
    最近更新 更多