反斜线和引号中的命令行参数斜线、引号、命令行、参数

由网友(回忆如困兽)分享简介:时的以下行为在C#.NET中的一些功能,或者一个错误?Is following behaviour some feature or a bug in C# .NET?测试应用程序:using System;using System.Linq;namespace ConsoleApplication1{clas...

时的以下行为在C#.NET中的一些功能,或者一个错误?

Is following behaviour some feature or a bug in 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();
        }
    }
}

使用命令行参数运行它:

Run it with command line arguments:

a "b" "x" "x"

在信号接收结果:

Arguments:
a
b
x
x"

Command Line:
a
"b"
"x"
"x"

有缺失反斜杠和非去除报价在args传递给方法的Main()。 有谁知道正确的解决办法,除了人工分析的CommandLine?

There are missing backslashes and non-removed quote in args passed to method Main(). Does anybody knows about correct workaround except manually parsing CommandLine?

推荐答案

根据这个article由乔恩·加洛韦,可以有怪异的行为经历了命令行参数使用反斜杠时。 最值得注意的是它提到,大多数应用程序(包括.Net应用程序)使用CommandLineToArgvW脱$ C C的命令行$。它采用疯狂逃逸这说明你所看到的行为规则。

According to this article by Jon Galloway, there can be weird behaviour experienced when using backslashes in command line arguments. Most notably it mentions that "Most apps (including .Net apps) use CommandLineToArgvW to decode their command lines. It uses crazy escaping rules which explain the behaviour you're seeing."

据解释说,第一套反斜杠不需要转义,但阿尔法后反斜杠来了(也许数字吗?)字符需要转义和引用总是需要进行转义。

It explains that the first set of backslashes do not require escaping, but backslashes coming after alpha (maybe numeric too?) characters require escaping and that quotes always need to be escaped.

,我相信得到你想要的,你就必须将它们作为参数:

Based off of these rules, I believe to get the arguments you want you would have to pass them as:

a "b" "x\" "x"

怪诞确实如此。

"Whacky" indeed.

阅读全文

相关推荐

最新文章