Getting raw (unsplit) command line in .NET

前提是你 提交于 2021-01-07 01:31:24

问题


In .NET, we can easily access split command line arguments in a string array from the argument of Main(string[]) or Environment.GetCommandLineArgs(). However, is there a way to get the unparsed command line as one string?

Background: my app is adding itself to FileExplorer context menu (like Notepad++ does). When it's launched this way, the filename is passed in without quoting, which means if there are spaces in the path, it's broken down. I know I can fix this by embrace %1 in quotation marks in the registry like myapp.exe "%1", but when I check other application's registry they didn't do so. They are plain like notepad.exe %1 - they got the complete command line. I want to know if it is possible in .NET and how.


回答1:


Try using: Environment.CommandLine




回答2:


To get the unparsed, raw, unmodified command line you have to P/Invoke GetCommandLine from kernel32. Some parsing will take place by the operating system. For example, an IO redirection such as >foo.txt will be excluded from the command line text regardless of the technique used.

Environment.CommandLine may be sufficient, but be aware that it removes interstitial spaces between arguments (unless the argument itself is enclosed in quotes) and it removes the quotes from quoted arguments.

For example, for the command line:

test.exe this is "a test"

Environment.CommandLine equals: "this is a test"

But GetCommandLine yields: "test.exe this is "a test"" with the spaces and quotes intact, along with the path of the exe.

Note that when using this technique, you have to parse the command line text manually, which may involve stripping off the path to the exe, which may itself be enclosed in quotes if the path contains spaces.



来源:https://stackoverflow.com/questions/65582647/preserving-command-line-arguments-in-windows

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!