1

I need to access the commandline from within a C# application. I can't find a way to detect mismatched double quotes if I use the "args" parameter.

The application I'm working on the moment has an option to encrypt a string that you pass to it via the commandline.

eg.

program.exe -encrypt somestring

Results in:

EZs/6rWxvJ82+VE8unJ0Xw==

Now if the user types in this:

program.exe -encrypt somestring extra characters

it ignores everything after "somestring" (you can still access the rest of the values through the "args" parameter).

You can workaround this easily using double quotes:

program.exe -encrypt "somestring extra characters"

And of course if you want to use embedded quotes you can escape them with "\":

program.exe -encrypt "somestring \"extra\" characters"

The problem occurs when the user inputs something like this:

program.exe -encrypt "somestring extra characters

or:

program.exe -encrypt somestring ex"tra characters

The program will completely ignore the double quote, which not be what the user was expecting. I would like to detect cases like these and inform the user about the mismatched/unescaped quote, otherwise they might end up with an encrypted version of the wrong string.

2 Answers 2

6

This is how the command line passes arguments to your C# program. You cannot change that. You can however access the command arguments string as a whole and perform the validation yourself.

MSDN: Environment.CommandLine Property

Sign up to request clarification or add additional context in comments.

Comments

0

Just do it manually: check that either you have only one argument after the -encrypt argument, and if not that the next argument starts with double quotes and the last argument ends with double quotes. If none of these happens throw a custom error to the user.

When the next argument after -encrypt starts with double quotes and the last argument ends with double quotes build the string yourself using Array.Copy or something of that kind.

2 Comments

The problem is that the quote gets completely ignored. ie. It doesn't show up as part of the value in the "args" parameter.
I see, sorry for not verifying this myself. You can just take all the arguments after -encrypt and join them to be the string, telling the user -encrypt must come last if you have more arguments to support.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.