首页 > 解决方案 > C# 参数 " 而不是反斜杠

问题描述

我的代码是

a.exe

string programName = AppDomain.CurrentDomain.FriendlyName;
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "b.exe"
proc.Arguments = programName + " \"" + AppDomain.CurrentDomain.BaseDirectory + "\"";
Process.Start(proc)

并检查另一个程序的值

b.exe

MessageBox.Show(args[0]);
MessageBox.Show(args[1]);

我预测值是

args[0] = a.exe
args[1] = D:\my test\with space\Folder\

但价值是

args[0] = a.exe
args[1] = D:\my test\with space\Folder"

问题

BaseDirectory : C:\my test\with space\Folder\
so i cover BaseDirectory with " because has space.
as a result i want
b.exe a.exe "C:\my test\with space\Folder\"
but at b.exe check args[1] value is
D:\my test\with space\Folder"

where is my backslash and why appear "

请帮帮我...

标签: c#arguments

解决方案


正如 Kayndarr 在评论中已经正确指出的那样,你正在逃避"你的道路。

由于其特殊含义,编译器不会将某些字符解释为字符串的一部分。

为了让编译器知道,您希望将这些字符解释为字符串的一部分,您必须将它们写成所谓的“转义序列”。

即,这意味着在它们前面放置一个反斜杠。

由于反斜杠本身因此也具有作为转义字符的特殊含义 - 如果您希望将斜杠解释为字符串的一部分,则必须转义斜杠。

"\\"

将生成一个带有一个反斜杠的文字字符串,因为第一个反斜杠用于转义第二个反斜杠。

因此,您示例中的修复将如下所示:

string programName = AppDomain.CurrentDomain.FriendlyName;
ProcessStartInfo proc = new ProcessStartInfo();
proc.FileName = "b.exe"
proc.Arguments = programName + "\\" + AppDomain.CurrentDomain.BaseDirectory + "\\";
Process.Start(proc);

推荐阅读