简体   繁体   中英

How do I parse command line arguments like Environment.GetCommandLineArgs() does?

I'm reading a shortcut using the COM "Windows Script Host Object Model" IWshRuntimeLibrary like this:

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

This gives me the arguments from the shortcut, say it looks like:

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

Which is not as a contrived example as you may 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'm thinking Regex, but this is beyond my bracketing.

[edit] I'd prefer a regex, but I'll look at the code and classes mentioned.

The rules seem to be:

  • Split on spaces,
  • unless the space is within double quotes (").
  • Strings within double quotes may contain double quotes escaped with a backslash (\\").
  • Other backslashes may appear on their own but should be treated as a normal character

The arguments and array in the previous two code sections would be an appropriate test.

[edit] https://stackoverflow.com/a/749653/350188 has answered my question. It calls the native system function and gives me exactly the same results as GetCommandLineArgs() with:

string[] splitArguments = CommandLineToArgs(arguments);

There's nothing really tricky about this. You can use basic C# syntax to examine the individual characters are parse out what you need.

For example, you can String.IndexOf() to locate specific characters you are looking for. And you can use String.Substring() to extract a portion of a string.

I've posted the code I did to parse a command line in the article AC# Command-Line Parser .

最简单,最可靠的解决方案是使用解析器的某些实现,例如, 这个或类似命令行解析器库的库取决于您在应用程序中到底需要什么。

如果只希望像GetCommandLineArgs这样的数组中的参数产生,则可以使用string.Split:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM