c# - 如何在 C# 中运行 Windows bash

标签 c# linux windows bash visual-studio

我想在 bash(Windows 中的 Linux 子系统)中运行以下命令:

bash -c "ls"

然后像这样在 C# 中使用它:

ProcessStartInfo info = new ProcessStartInfo("bash", "-c \"ls\"");
Process p = Process.Start(info);
p.WaitForExit();

但它给了我下面的异常(exception):

System.ComponentModel.Win32Exception was unhandled
  ErrorCode=-2147467259
  HResult=-2147467259
  Message=The system cannot find the file specified
  NativeErrorCode=2
  Source=System
  StackTrace:
       at System.Diagnostics.Process.StartWithShellExecuteEx(ProcessStartInfo startInfo)
       at System.Diagnostics.Process.Start()
       at System.Diagnostics.Process.Start(ProcessStartInfo startInfo)
       at ConsoleApplication1.Program.Main(String[] args) in c:\users\matin\documents\visual studio 2015\Projects\ConsoleApplication1\ConsoleApplication1\Program.cs:line 17
       at System.AppDomain._nExecuteAssembly(RuntimeAssembly assembly, String[] args)
       at System.AppDomain.ExecuteAssembly(String assemblyFile, Evidence assemblySecurity, String[] args)
       at Microsoft.VisualStudio.HostingProcess.HostProc.RunUsersAssembly()
       at System.Threading.ThreadHelper.ThreadStart_Context(Object state)
       at System.Threading.ExecutionContext.RunInternal(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state, Boolean preserveSyncCtx)
       at System.Threading.ExecutionContext.Run(ExecutionContext executionContext, ContextCallback callback, Object state)
       at System.Threading.ThreadHelper.ThreadStart()

编辑:

我可以成功运行包含我的命令的批处理文件。但我想像下面的代码一样获取输出:

ProcessStartInfo info = new ProcessStartInfo("file.bat");
info.RedirectStandardOutput = true;
info.UseShellExecute = false;
Process p = Process.Start(info);
while (!p.HasExited)
    Console.WriteLine(p.StandardOutput.ReadToEnd()); 

但它打印:

'bash' is not recognized as an internal or external command, operable program or batch file.

最佳答案

由于 Windows Filesystem Redirection 找不到文件对于 32 位应用程序。您必须将 .NET 应用程序编译为 x64 才能启动 C:\Windows\System32\bash.exe

但是,如果您尝试将 RedirectStandardOutput 设置为 true,您将得到的只是 E r r o r : 0 x 8 0 0 7 0 0 5 7 对应于 Win32 的 ERROR_INVALID_PARAMETER

我发现的一件事是,如果您没有将任何 Redirect 属性设置为 true,Bash 似乎会继承当前控制台,但是您甚至无法在启动 bash 的 .NET 程序...看来 Windows 目前不支持将 Linux 子系统应用程序的输出重定向到 Win32 应用程序。

关于c# - 如何在 C# 中运行 Windows bash,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39902379/

相关文章:

c# - 我如何断言使用 NUnit 调用了特定方法?

ios - OpenSSL 签名*完全*需要 AppleWWDRCA 证书吗?

vba - 控制ms以连续形式 Access 滚动条

windows - 通过编程将PC置于 sleep 模式

带有 Bootstrap 的 C# ASP.NET

c# - 在 COM Called Wrapper 中使用 .NET Generic List ToArray 会导致访问冲突,我是否遗漏了什么?

c# - 关闭 UserControl 时的事件是什么?

c - 如何从 IDE 编译 CHOLMOD 库 (SuiteSparse)

linux - 这行命令会做什么? grep ^..[l-z]$ 你好.txt

linux - 如何在 bash 中对某些命令进行 for 循环?