首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >从C#调用WSL bash.exe

从C#调用WSL bash.exe
EN

Stack Overflow用户
提问于 2018-04-03 18:30:27
回答 1查看 2.6K关注 0票数 9

主要是出于好奇,我用Ubuntu/WSL和Xming窗口服务器写了一个在Windows上启动Terminator shell的小应用。

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

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

代码语言:javascript
复制
C:\Windows\System32\bash.exe

然而,当我尝试运行这段代码时...

代码语言:javascript
复制
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();
}

我得到了错误...

代码语言:javascript
复制
System.ComponentModel.Win32Exception: 'The system cannot find the file specified'

检查我的整个系统的bash.exe显示它真的完全在另一个地方…

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

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

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

EN

回答 1

Stack Overflow用户

发布于 2019-05-16 08:32:33

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

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

代码语言:javascript
复制
            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();

            }
票数 4
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49627826

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档