views:

5516

answers:

6

I need to change the functionality of an application based on the executable name. Nothing huge, just changing strings that are displayed and some internal identifiers. The application is written in a mixture of native and .Net C++ code.

Two ways that I have looked at are to parse the GetCommandLine() function in Win32 and stuffing around with the AppDomain and other things in .Net. However using GetCommandLine won't always work as when run from the debugger the command line is empty. And the .Net AppDomain stuff seems to require a lot of stuffing around.

So what is the nicest/simplest/most efficient way of determining the executable name in C++/CLI? (I'm kind of hoping that I've just missed something simple that is available in .Net.)

Edit: One thing that I should mention is that this is a Windows GUI application using C++/CLI, therefore there's no access to the traditional C style main function, it uses the Windows WinMain() function.

+16  A: 

Call GetModuleFileName() using 0 as a module handle.

Ferruccio
+6  A: 

Use the argv argument to main:

int main(int argc, char* argv[])
{
    printf("%s\n", argv[0]);  //argv[0] will contain the name of the app.
    return 0;
}

You may need to scan the string to remove directory information and/or extensions, but the name will be there.

This solution has the added advantage of being cross-platform.
Adam Pierce
Yes it does, although I'm not looking for a cross platform one, just one for Windows using Win32 or .Net.
Daemin
That doesn't work in the general case.
tml
+1  A: 

There is a static Method on Assembly that will get it for you in .NET.

Assembly.GetEntryAssembly().FullName

Edit: I didn't realize that you wanted the file name... you can also get that by calling:

Assembly.GetEntryAssembly().CodeBase

That will get you the full path to the assembly (including the file name).

Brian ONeil
While this seemed the way to go initially, it actually does not work in practice, as the assembly name is the same regardless of what the executable name gets set to.
Daemin
+3  A: 

Ferruccio's answer is good. Here's some example code:

TCHAR exepath[MAX_PATH];

if(0 != GetModuleFileName(0, exepath, MAX_PATH))
    MessageBox(_T("Error!"));

MessageBox(exepath, _T("My executable name"));
Adam Pierce
+1  A: 

Use __argv[0]

A: 

Not an answer, but I was just thinking this could make a great easter egg in some program.

Have some sort of extra show up in the file name is some weird keyword :P

Coal