简体   繁体   English

在 .NET 中获取原始(未拆分)命令行

[英]Getting raw (unsplit) command line in .NET

In .NET, we can easily access split command line arguments in a string array from the argument of Main(string[]) or Environment.GetCommandLineArgs() .在 .NET 中,我们可以从Main(string[])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).背景:我的应用程序将自己添加到 FileExplorer 上下文菜单中(就像 Notepad++ 那样)。 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.我知道我可以通过在注册表中包含引号%1来解决这个问题,例如myapp.exe "%1" ,但是当我检查其他应用程序的注册表时,他们没有这样做。 They are plain like notepad.exe %1 - they got the complete command line.它们就像notepad.exe %1一样简单——它们得到了完整的命令行。 I want to know if it is possible in .NET and how.我想知道在 .NET 中是否可行以及如何实现。

尝试使用: Environment.CommandLine

Try: 尝试:

Environment.CommandLine Environment.CommandLine

This better make it to 30 characters. 这最好使它达到30个字符。

To get the unparsed, raw, unmodified command line you have to P/Invoke GetCommandLine from kernel32.要获得未解析的、原始的、未修改的命令行,您必须从 kernel32 P/Invoke GetCommandLine 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.例如,无论使用何种技术,诸如>foo.txt类的 IO 重定向都将从命令行文本中排除。

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. Environment.CommandLine 可能就足够了,但请注意,它会删除参数之间的间隙(除非参数本身包含在引号中)并从带引号的参数中删除引号。

For example, for the command line:例如,对于命令行:

test.exe this is "a test"

Environment.CommandLine equals: " this is a test " Environment.CommandLine 等于:“ 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.但是 GetCommandLine 产生:“ test.exe this is "a test" ,空格和引号完好无损,以及 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.请注意,在使用此技术时,您必须手动解析命令行文本,这可能涉及剥离 exe 的路径,如果路径包含空格,则该路径本身可能用引号引起来。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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