Nick X Tsui
Nick X Tsui

Reputation: 2912

Path can matter launching .exe from C#?

I am having trouble launching a .exe from my C# code due to difference in path where the .exe is stored.

Here is how I launched the command line .exe

try
{
    System.Diagnostics.Process process = new System.Diagnostics.Process();
    System.Diagnostics.ProcessStartInfo startInfo = new System.Diagnostics.ProcessStartInfo();
    startInfo.WindowStyle = System.Diagnostics.ProcessWindowStyle.Hidden;
    startInfo.FileName = "cmd.exe";
    startInfo.Arguments = fijiCmdText;
    process.StartInfo = startInfo;
    process.Start();
    _processOn = true;
    process.WaitForExit();

    ret = 1;
}
catch (Exception ex)
{
    ret = 0;
}

Basically fijiCmdText is the command line that gets executed.

However, the problem is, for fijiCmdText, something like this will succeed:

fijiCmdText = "/C D:\\fiji\\ImageJ-win64.exe -macro D:\\fiji\\macros\\FFTBatch.ijm C:\\Users\\myAccount\\Documents\\Untitled005\\ --headless"

but something like this will NOT succeed:

fijiCmdText = "/C C:\\Users\\myAccount\\Downloads\\fiji (1)\\ImageJ-win64.exe -macro D:\\fiji\\macros\\FFTBatch.ijm C:\\Users\\myAccount\\Documents\\Untitled005\\ --headless"

It seems the location of the .exe matters. So I am wondering, other than changing the location of the .exe, is there anyway I can handle this in C# code, making it more flexible and reliable to handle different path? Thanks.

EDIT: Both run no problem using command line.

Upvotes: 0

Views: 130

Answers (1)

Tim S.
Tim S.

Reputation: 56536

The problem is that the second path contains a space, but doesn't have quotes delimiting it. Try this:

fijiCmdText = "/C \"C:\\Users\\myAccount\\Downloads\\fiji (1)\\ImageJ-win64.exe\" -macro D:\\fiji\\macros\\FFTBatch.ijm C:\\Users\\myAccount\\Documents\\Untitled005\\ --headless"

If the string is built using, e.g. a string.Format like this:

fijiCmdText = string.Format("/C {0} -macro {1} {2} --headless",
                            path1, path2, path3);

Then you should change it to wrap all paths in quotes, e.g.:

fijiCmdText = string.Format("/C \"{0}\" -macro \"{1}\" \"{2}\" --headless",
                            path1, path2, path3);

Upvotes: 3

Related Questions