David White
David White

Reputation: 141

C# pass path in argument

I'm starting cmd as a process in C# and I want to pass a file path in the argument. How to do it?

Process CommandStart = new Process();
CommandStart.StartInfo.UseShellExecute = true;
CommandStart.StartInfo.RedirectStandardOutput = false;
CommandStart.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
CommandStart.StartInfo.FileName = "cmd";
CommandStart.StartInfo.Arguments = "(here i want to put a file path to a executable) -arg bla -anotherArg blabla < (and here I want to put another file path)";
CommandStart.Start();
CommandStart.WaitForExit();
CommandStart.Close();

EDIT:

        Process MySQLDump = new Process();
        MySQLDump.StartInfo.UseShellExecute = true;
        MySQLDump.StartInfo.RedirectStandardOutput = false;
        MySQLDump.StartInfo.WindowStyle = ProcessWindowStyle.Hidden;
        MySQLDump.StartInfo.FileName = "cmd";
        MySQLDump.StartInfo.Arguments = "/c \"\"" + MySQLDumpExecutablePath + "\" -u " + SQLActions.MySQLUser + " -p" + SQLActions.MySQLPassword + " -h " + SQLActions.MySQLServer + " --port=" + SQLActions.MySQLPort + " " + SQLActions.MySQLDatabase + " \" > " + SQLActions.MySQLDatabase + "_date_" + date + ".sql";
        MySQLDump.Start();
        MySQLDump.WaitForExit();
        MySQLDump.Close();

Upvotes: 0

Views: 3499

Answers (1)

keyboardP
keyboardP

Reputation: 69372

You need to put the file path in double quotes and use a verbatim string literal (@) as SLaks mentioned.

CommandStart.StartInfo.Arguments = @"""C:\MyPath\file.exe"" -arg bla -anotherArg";

Example with an OpenFileDialog

using(OpenFileDialog ofd = new OpenFileDialog())
{
    if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.OK)
    {
       string filePath = "\"" + ofd.FileName + "\"";

       //..set up process..

       CommandStart.StartInfo.Arguments = filePath + " -arg bla -anotherArg";
    }
 }

Update to comment

You can format your string using String.Format.

string finalPath = String.Format("\"{0}{1}_date_{2}.sql\"", AppDomain.CurrentDomain.BaseDirectory, SQLActions.MySQLDatabase, date);

Then pass finalPath into the arguments.

Upvotes: 1

Related Questions