以下行为是 C# .NET 中的某些特性还是错误?
测试应用:
using System;
using System.Linq;
namespace ConsoleApplication1
{
class Program
{
static void Main(string[] args)
{
Console.WriteLine("Arguments:");
foreach (string arg in args)
{
Console.WriteLine(arg);
}
Console.WriteLine();
Console.WriteLine("Command Line:");
var clArgs = Environment.CommandLine.Split(' ');
foreach (string arg in clArgs.Skip(clArgs.Length - args.Length))
{
Console.WriteLine(arg);
}
Console.ReadKey();
}
}
}
使用命令行参数运行它:
a "b" "\\x\\" "\x\"
在我收到的结果中:
Arguments:
a
b
\\x\
\x"
Command Line:
a
"b"
"\\x\\"
"\x\"
传递给方法 Main() 的参数中缺少反斜杠和未删除的引号。除了手动解析 Environment.CommandLine
之外,正确的解决方法是什么?
最佳答案
根据这个article by Jon Galloway ,在命令行参数中使用反斜杠时可能会出现奇怪的行为。
最值得注意的是它提到“大多数应用程序(包括 .NET 应用程序)使用 CommandLineToArgvW 来解码它们的命令行。它使用疯狂的转义规则来解释您所看到的行为。”
它解释说,第一组反斜杠不需要转义,但在字母(可能也是数字?)字符之后的反斜杠需要转义,并且引号始终需要转义。
根据这些规则,我相信要获得您想要的参数,您必须将它们传递为:
a "b" "\\x\\\\" "\x\\"
确实“古怪”。
MS blog entry 在 2011 年讲述了疯狂逃避规则的完整故事: "每个人都以错误的方式引用命令行参数"
Raymond also had something to say on the matter (早在 2010 年):“CommandLineToArgvW 对引号和反斜杠的奇怪处理是怎么回事”
这种情况一直持续到 2020 年,Everyone quotes command line arguments the wrong way 中描述的转义规则截至 2020 年和 Windows 10 仍然正确。
关于c# - 命令行参数中的反斜杠和引号,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9287812/