2013-07-12 180 views
0

我以cmd作爲C#中的進程開始,我想在參數中傳遞一個文件路徑。怎麼做?C#在參數中傳遞路徑

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(); 

編輯:

 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(); 
+0

你想達到什麼目的? – Tigran

+0

執行一個可執行文件,該文件接受參數並返回可存儲在文件中的數據。 –

回答

1

你需要把文件路徑用雙引號,並使用所提到SLaks一個逐字字符串(@)。

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

例如用一個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"; 
    } 
} 

更新評論

可以使用String.Format格式化字符串。

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

然後通過finalPath進入參數。

+2

使用逐字字符串文字。 – SLaks

+0

我試圖運行mysqldump.exe,傳遞credentails參數,然後指定導出文件。我怎樣才能在路徑中自動添加雙斜槓,因爲通過filebrowser用戶選擇了他的mysqldump.exe,並且該URL不被應用程序操縱。 –

+0

@DavidWhite轉義(雙斜槓\ verbtaim字符串文字)僅用於輸入源代碼中的路徑。您不需要在運行時執行該操作,只需在文件路徑前後添加雙引號(更新後的答案),以便在路徑中存在空格的情況下仍將其視爲一個參數。 – keyboardP