I want to run the following command in bash (Linux Subsystem in Windows) :
bash -c "ls"
And use it in C# like this:
ProcessStartInfo info = new ProcessStartInfo("bash", "-c \"ls\"");
Process p = Process.Start(info);
p.WaitForExit();
But it gives me the exception below:
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()
Edit:
I can successfully run a batch file contains my command. But I want to grab the output like the code below:
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());
But it prints:
'bash' is not recognized as an internal or external command, operable program or batch file.
The file cannot be found due to Windows Filesystem Redirection for 32-bit apps. You have to compile your .NET app as x64 in order to launch C:\Windows\System32\bash.exe
.
If you try and set RedirectStandardOutput
to true
, however, all you'll get is E r r o r : 0 x 8 0 0 7 0 0 5 7
which corresponds to Win32's ERROR_INVALID_PARAMETER
.
One thing I have discovered is that if you do not set any of the Redirect
properties to true, Bash appears to inherit the current console, however you can't then even redirect standard output on the .NET program that launches bash... it would appear that Windows currently doesn't support redirecting output from a Linux Subsystem application into a Win32 one.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With