jgetner
jgetner

Reputation: 703

Handle spaces in path for cmd

So I'm building a command to run through cmd.exe. But the command seems to fail due to the space in some directory names.

process.StandardInput.WriteLine(this.phpPath + " " + this.phpUnitPath + " " + itemChecked);

Upvotes: 0

Views: 2656

Answers (4)

Ken Kin
Ken Kin

Reputation: 4693

Put whatever numbers of partial path in the first array in following statement:

var path=String.Join((new[] { this.phpPath, this.phpUnitPath, itemChecked }).Aggregate((a, b) => a+"\x20"+b), new[] { '\"', '\"' });

Upvotes: 0

Jonathon Reinhart
Jonathon Reinhart

Reputation: 137438

You say that you're using cmd.exe but you're writing out data to a Process's stdin. I'm assuming that process is a cmd.exe instance you've started.

A possibly better way would be to use the /C switch:

C:\Users\Jonathon>cmd /?
Starts a new instance of the Windows command interpreter

CMD [/A | /U] [/Q] [/D] [/E:ON | /E:OFF] [/F:ON | /F:OFF] [/V:ON | /V:OF
    [[/S] [/C | /K] string]

/C      Carries out the command specified by string and then terminates
...

Either way you go, all paths with spaces in them need to be enclosed in quotes.

As a final note, are you sure you even need to be using cmd.exe ? Why not just execute the program you actually want to run directly?

Upvotes: 0

Daniel Imms
Daniel Imms

Reputation: 50189

The typical way to pass text with spaces in a command line is to wrap it in quotes like this:

app "c:\my apps\blah.exe" "some argument"

Try doing something like this:

string path = this.phpPath + " " + this.phpUnitPath + " " + itemChecked
string cmd = string.Format("\""{0} {1} {2}"\"", 
    this.phpPath, this.phpUnitPath, itemChecked);

Upvotes: 1

Botz3000
Botz3000

Reputation: 39620

Just put the path between double quotes:

string command = "\"" + someFilePathWithSpaces + "\"";

Upvotes: 2

Related Questions