【发布时间】:2016-10-06 17:37:50
【问题描述】:
我想在 bash(Windows 中的 Linux 子系统)中运行以下命令:
bash -c "ls"
并像这样在 C# 中使用它:
ProcessStartInfo info = new ProcessStartInfo("bash", "-c \"ls\"");
Process p = Process.Start(info);
p.WaitForExit();
但它给了我以下例外:
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.
【问题讨论】:
-
你试过
new ProcessStartInfo("C:\Program Files\Git\git-bash.exe")吗? -
试试bash的全路径名
-
@cup 没区别
-
如果全名有空格,需要用引号括起来。
-
我们可以假设
ls是一个更复杂的命令序列的占位符吗?在bash -c中运行它本身是毫无意义的。
标签: c# linux windows bash visual-studio