2013-02-10 183 views
2

我想將路徑字符串作爲參數傳遞給Windows窗體應用程序。我知道我需要添加引號。我目前使用下面的代碼。將路徑作爲參數傳遞

DirectoryInfo info = new DirectoryInfo(path); 
string.Format("\"{0}\"", info.FullName); 

上面的代碼在路徑如D:\My Development\GitRepositories時工作。但是,當我通過C:\我得到的論點是C:",因爲最後\字符作爲轉義字符工作。

我做錯了什麼?另外,有沒有更好的方法來做到這一點?

在此先感謝。

+0

你需要躲避轉義字符,「\\」將導致爲「\」 – Machinarius 2013-02-10 16:02:47

+1

的問題是不與您發佈的代碼,而是在代碼使用'string.Format(「\」{0} \「」,info.FullName);'的結果。發佈它,我們將嘗試確定你做錯了什麼。 – 2013-02-10 16:03:09

+0

您沒有分配字符串格式的結果。你應該這樣做:'string result = string.Format(「\」{0} \「」,info.FullName);' – 2013-02-11 20:35:43

回答

0

您的問題是逃脫在C#中,你可以掩蓋所有的反斜線與第二反斜槓或第一次報價之前把at符號(@):

string option1="c:\\your\\full\\path\\"; 
string [email protected]"c:\your\full\path\"; 

反正不是在任何情況下都是報價轉換爲字符串所必要的。在大多數情況下,只要你需要啓動一個外部程序,並且只有當你需要這個參數的時候。

1

CommandLineArgspace分隔,因此u需要傳遞命令-ARG與"

這意味着如果路徑= C:\My folder\將作爲兩個參數被髮送,但是,如果它作爲"C:\My Folder\"通過了它是一個參數。

所以

string commandArg = string.Format("\"{0}\"", info.FullName) 
1

嘗試使用的ProcessStartInfo和Process類和派生應用程序。這也會讓你更好地控制它的啓動方式以及它返回的輸出或錯誤。 (不是所有的選項都在,當然這個例子所示)

DirectoryInfo info = new DirectoryInfo(path); 

ProcessStartInfo processInfo = new ProcessStartInfo(); 
processInfo.FileName = [you WinForms app]; 
processInfo.Arguments = String.Format(@"""{0}""", info.FullName); 
using (Process process = Process.Start(processInfo)) 
{ 
    process.WaitForExit(); 
}