0

In a C#.NET console application, the string[] args that Main takes already takes care of quoted parameters when those params are quoted with doublequotes; for example, the following commandline:

MyProgram.exe A "B C D" E

... will result in only 3 entries in args. However when using single quotes instead:

MyProgram.exe A 'B C D' E

... then args will have 5 entries. The single quotes haven't turned B C D into a single parameter.

Is there a way of getting .NET to also treat single quotes as valid commandline argument quoting characters, or does this require a special commandline argument parsing library?

Jez
  • 27,951
  • 32
  • 136
  • 233
  • 1
    Don't write your own argument parser; [there's **loads** of them out there already](http://stackoverflow.com/questions/491595/best-way-to-parse-command-line-arguments-in-c), and most of them are probably better at it than your home-rolled will be (unless you really want to spend time on implementing argument parsing, that is). – Tomas Aschan Mar 03 '16 at 07:55

1 Answers1

2

You can access the whole line via

  Environment.CommandLine

And handle the single quotes manually

One way to extract the CommandArg-Line only could be:

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

            return commandArgLine;
        }

Hint: Do not use System.Reflection.Assembly.GetExecutingAssembly().Location in your debug environment if the vs-host process is enabled - will not return the right location in this case (Thats why i read the last ")

Cadburry
  • 1,844
  • 10
  • 21
  • Are you sure that the program name is guaranteed to be enclosed in quotes? [MSDN doesn't seem to indicate this](https://msdn.microsoft.com/en-us/library/system.environment.commandline(v=vs.110).aspx). – vgru Mar 03 '16 at 07:56
  • I have not tried it in different paths - right - may there are no quotes - so its maybe better to call GetCommandLineArgs() - and join the string[] into one string.... – Cadburry Mar 03 '16 at 08:02