mo alaz
mo alaz

Reputation: 4749

Starting an executable and passing arguments

I have definitely done something like this before, but something is not working right and I'm not 100% sure what it is.

I have an executable executable.exe that takes a file, does some magic and outputs a second file somewhere else. So when I run this executable via CMD, all I need to do is pass "path1" and "path2". I put the paths in quotations because they may have spaces.

Anyway, so what I'm doing in my c# application is something like:

public void methodToRunExecutable()
{
var exePath = "\""+ "C:\\SomePathToAnExecutable" + "\"";
var firstFilePath = "C:\\PathToFirstFile\\NameOfFile.txt"
var secondFilePath= "C:\\PathToSecondFile\\NameOfFile.txt"

Process.Start(exePath, "\""firstFilePath + "\" \"" + secondFilePath+"\"")
}

However, I notice when I'm debugging is that the "\"" is actually showing up as \", like the backslash isn't escaping the quotation mark.

To be clear, when I run the CMD exe all I have to do is:

"C:\\PathToFirstFile\\NameOfFile.txt" "C:\\PathToSecondFile\\NameOfFile.txt"

and it works great. Any Ideas on what I'm doing wrong? Is it because the " is not being escaped?

Upvotes: 0

Views: 123

Answers (1)

Bob Horn
Bob Horn

Reputation: 34297

Escaping is ugly and error prone. Use @ and you won't need to escape:

var firstFilePath = @"C:\PathToFirstFile\NameOfFile.txt"

It might also be easier to use Process this way:

using (Process process = new Process())
{
    process.StartInfo.FileName = exePath;
    process.StartInfo.Arguments = ""; // args here
    process.Start();
}

Upvotes: 2

Related Questions