Search code examples
c#commandlineexecute

C# Execute command Line error with space


Here is my code:

ProcessStartInfo startInfo = new ProcessStartInfo();
startInfo.FileName = "cmd.exe";
String mypath = Assembly.GetExecutingAssembly().Location.ToString();
mypath = mypath.Substring(0, mypath.LastIndexOf("\\"));
startInfo.Arguments = "/k "+
    string.Format("\"{0}\"" + " " + ProcessIds[clientlist.SelectedIndex] + " " + "\"{1}\"",
                  mypath + "\\MIMT.exe",
                  mypath + "\\No.Ankama.dll");
process.StartInfo = startInfo;
process.Start();

And now the result:

screenshot

Looks like the space is a problem, despite the quote, I do not understand.


Solution

  • Don't parse the path and file name with Substring() or similar methods.

    Use Path.GetDirectoryName() and Path.Combine().

    string mypath = Path.GetDirectoryName(System.Reflection.Assembly.GetExecutingAssembly().Location);
    string exeFile = Path.Combine(mypath, "MIMT.exe");
    string dllFile = Path.Combine(mypath, "No.Ankama.dll");
    startInfo.Arguments = "/k \""+ exeFile + "\" " + ProcessIds[clientlist.SelectedIndex] 
        + " \"" + dllFile + "\"";
    

    UPDATE:

    You can run your exe file directly without using the cmd.exe.

    startInfo.FileName = exeFile;
    startInfo.Arguments = ProcessIds[clientlist.SelectedIndex] + " \"" + dllFile + "\"";