Last active
May 19, 2020 21:48
-
-
Save RickStrahl/b5a9b3e4ca211124f6e05ab0161a0793 to your computer and use it in GitHub Desktop.
Trying to run `bash -c ""` command with Process.Start/ShellExecute
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
// works in LinqPad | |
void Main() | |
{ | |
ExecuteCommandLine("wt"); // works - this is resolved | |
ExecuteCommandLine("bash"); // The system cannot find the file specified | |
// actual command line I'm trying to fire | |
ExecuteCommandLine("bash -c \"cd /mnt/c/projects/Test/jekyll/help; bundle exec jekyll serve\""); | |
} | |
public void ExecuteCommandLine(string fullCommandLine, | |
string workingFolder = null, | |
int waitForExitMs = 0, | |
string verb = "OPEN", | |
ProcessWindowStyle windowStyle = ProcessWindowStyle.Normal) | |
{ | |
string executable = fullCommandLine; | |
string args = null; | |
if (executable.StartsWith("\"")) | |
{ | |
int at = executable.IndexOf("\" "); | |
if (at > 0) | |
{ | |
args = executable.Substring(at+1).Trim(); | |
executable = executable.Substring(0, at); | |
} | |
} | |
else | |
{ | |
int at = executable.IndexOf(" "); | |
if (at > 0) | |
{ | |
if (executable.Length > at +1) | |
args = executable.Substring(at + 1).Trim(); | |
executable = executable.Substring(0, at); | |
} | |
} | |
// this also doesn't work | |
// ShellExecute(IntPtr.Zero,verb,executable,args,workingFolder,(int) windowStyle); | |
var pi = new ProcessStartInfo(); | |
pi.UseShellExecute = true; | |
pi.Verb = verb; | |
pi.WindowStyle = windowStyle; | |
pi.FileName = executable; | |
pi.WorkingDirectory = workingFolder; | |
pi.Arguments = args; | |
using (var p = Process.Start(pi)) | |
{ | |
if (waitForExitMs > 0) | |
{ | |
if (!p.WaitForExit(waitForExitMs)) | |
throw new TimeoutException("Process failed to complete in time."); | |
} | |
} | |
} | |
[DllImport("Shell32.dll", CharSet = CharSet.Auto, SetLastError = true)] | |
static extern IntPtr ShellExecute(IntPtr hwnd, string lpOperation, string lpFile, string lpParameters, string lpDirectory, int nShowCmd); | |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment