How to run windows bash in c #

I want to run the following command in bash (Linux subsystem on Windows):

bash -c "ls"

And use it in C # as follows:

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

But this gives me an 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 the batch file containing my command. But I want to get the output as shown 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 he prints:

'bash' is not recognized as an internal or external command, operable program or batch file.
+4
source share
3 answers

File not found due to Windows file system redirection for 32-bit applications. You must compile your .NET application as x64 to run 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, , , .NET- bash... , Windows Linux Win32.

+3

:

bash -c "ls > log.txt"

# :

ProcessStartInfo info = new ProcessStartInfo("file.bat");
Process p = Process.Start(info);
p.WaitForExit();
Console.WriteLine(File.ReadAllText("log.txt"));

log.txt.

:

  • cmd .
  • .

, .

0

, , .

string strCmdText;
strCmdText= "bash -c \"time\"";
System.Diagnostics.Process.Start("CMD.exe",strCmdText);
-1

Source: https://habr.com/ru/post/1656971/


All Articles