2013-02-10 126 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(); 
} 
相关问题