我想在 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/