开发者

Trapping command line parameters from C# code

Suppose I have typed excel.exe /r "c:\book1.xlsx" in the Run Window.

How will I trap the switch(/r) and the parameter "c:\book1.xlsx" from my C# cod开发者_JAVA百科e?

Thanks


If your code is running in-process (in excel.exe)

You can get the command-line via the Environment.CommandLine property. Note that a process can change it's own command-line (it's just some bytes in memory, after all), but this is not often done.

If your code is running out-of-process (option 1, recommended)

You can use WMI to get another process' command-line arguments. See here. You'll need to add a reference to System.Management.dll. For example:

string query = string.Format("SELECT CommandLine FROM Win32_Process WHERE Name='{0}'", "excel.exe");

using (ManagementObjectSearcher searcher = new ManagementObjectSearcher(query))
{
    foreach (ManagementObject process in searcher.Get())
    {
        Console.WriteLine(process["CommandLine"]);
    }
}

This will print the command lines of all running instances of excel.exe. You can also query by process ID by using the ProcessId parameter in place of the Name parameter in the query.

If your code is running out-of-process (option 2, trickier)

You can also get a remote process' command-line by using NtQueryInformationProcess and ReadProcessMemory to read in the process environment block (PEB) to get to the _RTL_USER_PROCESS_PARAMETERS which contains the command-line. None of this stuff is documented, however, which means that it's unsupported and subject to change. The details of doing this are outlined here.


Command line parameters without options

Example: yourExecutable.exe parameter1 parameter2 parameter3

Refer: http://msdn.microsoft.com/en-us/library/aa288457%28VS.71%29.aspx

Command line parameters with options - There are no standard parsers available. You either need to write your own or borrow

Example: yourExecutable.exe -f fileName --create

Refer: http://www.codeproject.com/KB/recipes/command_line.aspx

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜