【问题标题】:How to use single quotes instead of doublequotes for C# console params?如何为 C# 控制台参数使用单引号而不是双引号?
【发布时间】:2016-06-15 09:22:59
【问题描述】:

在 C#.NET 控制台应用程序中,Main 使用的 string[] args 在用双引号引用这些参数时已经处理了引用的参数;例如,以下命令行:

MyProgram.exe A "B C D" E

... 将导致args 中只有 3 个条目。但是,当使用单引号时:

MyProgram.exe A 'B C D' E

... 那么args 将有 5 个条目。单引号还没有将B C D 变成单个参数。

有没有办法让 .NET 也将单引号视为有效的命令行参数引用字符,或者这是否需要特殊的命令行参数解析库?

【问题讨论】:

  • 不要编写自己的参数解析器; there's loads of them out there already,而且他们中的大多数人可能比你的家庭滚动做得更好(除非你真的想花时间实现参数解析)。

标签: c# .net command-line parameters console-application


【解决方案1】:

您可以通过

访问整行
  Environment.CommandLine

并手动处理单引号

仅提取 CommandArg-Line 的一种方法可能是:

private static string getCommandLineArgLine()
        {
            string fullCommandLine = Environment.CommandLine;
            int applicationDoubleQuoteEnds = fullCommandLine.IndexOf("\"", 1, StringComparison.InvariantCulture);
            string commandArgLine = fullCommandLine.Substring(applicationDoubleQuoteEnds + 1).TrimStart();

            return commandArgLine;
        }

提示:如果启用了 vs-host 进程,请不要在调试环境中使用System.Reflection.Assembly.GetExecutingAssembly().Location - 在这种情况下不会返回正确的位置(这就是为什么我阅读最后一个“)

【讨论】:

  • 你确定程序名保证用引号括起来吗? MSDN doesn't seem to indicate this.
  • 我没有在不同的路径中尝试过 - 对 - 可能没有引号 - 所以最好调用 GetCommandLineArgs() - 并将字符串 [] 加入一个字符串......跨度>
猜你喜欢
  • 2011-05-18
  • 1970-01-01
  • 2013-04-22
  • 2011-12-08
  • 1970-01-01
  • 2017-07-09
  • 1970-01-01
  • 2011-12-29
  • 2018-07-01
相关资源
最近更新 更多