How to handle command line arguments like Environment.GetCommandLineArgs ()?

I am reading a shortcut using COM "Windows Script Host Object Model" IWshRuntimeLibrary as follows:

IWshShell wsh = new WshShellClass(); IWshShortcut sc = (IWshShortcut)wsh.CreateShortcut(shortcutFile); string arguments = sc.Arguments; 

This gives me the arguments from the shortcut, let's say it looks like this:

 -a "c:\temp\a 1.txt" -b "b.exe -c \"c:\temp\c -2.txt\" -d d.txt" -e test 

This is not a far-fetched example, what do you think ... How can I do the same as GetCommandLineArgs and get:

 args {string[6]} [0] = "-a" [1] = "c:\\temp\\a 1.txt" [2] = "-b" [3] = "b.exe -c \"c:\\temp\\c -2.txt\" -d d.txt" [4] = "-e" [5] = "test" 

I think Regex, but this is above my bracketing.

[edit] I would prefer a regular expression, but I will look at the code and classes mentioned.

The rules look like this:

  • Divide into spaces
  • if the space is not in double quotation marks (").
  • Double quoted strings may contain double quotes escaped with a backslash (\ ").
  • Other backslashes may appear on their own, but should be treated as normal characters.

Arguments and an array in the previous two sections of code would be a suitable test.

[edit] https://stackoverflow.com/a/3184168/ answered my question. It calls its own system function and gives me the same results as GetCommandLineArgs (), with:

 string[] splitArguments = CommandLineToArgs(arguments); 
+4
source share
3 answers

This is nothing complicated. You can use the basic C # syntax to examine individual characters in order to parse what you need.

For example, you can String.IndexOf() find the specific characters you are looking for. And you can use String.Substring() to extract part of the string.

I published the code I did for parsing the command line in A C # Command-Line Parser article.

+1
source

The simplest and most reliable solution will be to use some parser implementation, for example this one or a library, for example, the Parser library for the command line depends on what exactly you need in your application.

0
source

If you just need the arguments in an array of type GetCommandLineArgs, you can use string.Split:

 string[] args = arguments.Split(' '); 
-3
source

All Articles