命令行参数中的反斜杠和引号 [英] Backslash and quote in command-line arguments

查看:399
本文介绍了命令行参数中的反斜杠和引号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下行为是C#.NET中的某些功能还是bug?

Is the 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();
        }
    }
}

使用命令行参数运行:

a "b" "\\x\\" "\x\"

结果是:

Arguments:
a
b
\\x\
\x"

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

传递给方法Main()的args中缺少反斜杠和引号,除了手动解析 Environment.CommandLine

There are missing backslashes and non-removed quote in args passed to method Main(). What is the correct workaround except manually parsing Environment.CommandLine?

推荐答案

根据此 Jon Galloway的文章,在命令中使用反斜杠时可能会出现奇怪的行为

According to this article by Jon Galloway, there can be weird behaviour experienced when using backslashes in command line arguments.

最值得注意的是,它提到 最常用的Ons(包括.NET应用程序)使用CommandLineToArgvW对其命令行进行解码。它使用疯狂的转义规则来解释您所看到的行为。

Most notably it mentions that "Most applications (including .NET applications) 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\\"

实际上是怪胎。

在2011年, MS博客条目每个人都以错误的方式引用了命令行参数

雷蒙德也有东西g在此问题上说(早在2010年): CommandLineToArgvW对引号和反斜杠的奇怪处理是怎么回事

Raymond also had something to say on the matter (already back in 2010): "What's up with the strange treatment of quotation marks and backslashes by CommandLineToArgvW"

这种情况一直持续到2020年, 每个人都以错误的方式引用命令行参数 到2020年和Windows 10仍然是正确的。

The situation persists into 2020 and the escaping rules described in Everyone quotes command line arguments the wrong way are still correct as of 2020 and Windows 10.

这篇关于命令行参数中的反斜杠和引号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆