在 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 也将单引号视为引用字符的有效命令行参数,或者这是否需要特殊的命令行参数分析库?
您可以通过以下方式访问整条线路
Environment.CommandLine
并手动处理单引号
仅提取命令参数行的一种方法是:
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
- 在这种情况下不会返回正确的位置(这就是我阅读最后一个的原因")