传递路径作为参数

时间:2013-02-10 15:58:16

标签: c# command-line-arguments

我正在尝试将路径字符串作为参数传递给Windows窗体应用程序。我知道我需要添加引号。我目前正在使用以下代码。

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

当路径类似D:\My Development\GitRepositories时,上面的代码有效。但是,当我传递C:\时,我得到的参数是C:",因为最后\个字符作为转义字符。

我做错了吗?另外,有更好的方法吗?

提前致谢。

3 个答案:

答案 0 :(得分:2)

尝试使用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();
}

答案 1 :(得分:1)

CommandLineArgspace分隔,因此您需要使用"传递命令arg

这意味着如果Path = C:\My folder\将作为两个参数发送,但如果它作为"C:\My Folder\"传递,则它是一个参数。

所以

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

答案 2 :(得分:0)

您的问题是在C#中转义,您可以使用第二个反斜杠屏蔽所有反斜杠或在第一个引号前放置一个at符号(@):

string option1="c:\\your\\full\\path\\";
string option2=@"c:\your\full\path\";

无论如何不是在每种情况下引用字符串nessesary。在大多数情况下,只需要启动一个外部程序,只有当你需要这个作为参数时才这样。