3

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

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

上面的代码在 path 像D:\My Development\GitRepositories. 但是,当我通过C:\参数时,我得到的是C:"因为最后一个\字符用作转义字符。

难道我做错了什么?另外,有没有更好的方法来做到这一点?

提前致谢。

4

3 回答 3

2

Try using ProcessStartInfo and the Process class and spawn your application. This will also give you much more control over how it is launched and any output or errors it returns. (not all options are shown in this example of course)

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();
}
于 2013-02-11T20:28:44.583 回答
1

Your problem is escaping in C# you could mask all backslashes with a second backslash or put an at sign (@) before the first quote:

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

Anyway not in every case are quotes into a string nessesary. In most cases just if you need to start an external programm and this only if you need this as an argument.

于 2013-02-10T16:06:12.287 回答
1

CommandLineArgspace分隔的,因此你需要传递命令参数"

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

所以

string commandArg = string.Format("\"{0}\"", info.FullName)
于 2013-02-10T16:08:37.697 回答