[ACCEPTED]-How to get the application executable name in WindowsC++/CLI?-c++-cli

Accepted answer
Score: 39

Call GetModuleFileName() using 0 as a module handle.

Note: you can also 8 use the argv[0] parameter to main or call GetCommandLine() if there 7 is no main. However, keep in mind that these 6 methods will not necessarily give you the 5 complete path to the executable file. They 4 will give back the same string of characters 3 that was used to start the program. Calling 2 GetModuleFileName(), instead, will always give you a complete 1 path and file name.

Score: 14

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

TCHAR exepath[MAX_PATH+1];

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

MessageBox(exepath, _T("My executable name"));
Score: 8

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 3 the string to remove directory information 2 and/or extensions, but the name will be 1 there.

Score: 4

Use __argv[0]

0

Score: 3

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

Assembly.GetEntryAssembly().FullName

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

Assembly.GetEntryAssembly().CodeBase

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

Score: 0

I can confirm it works under win64/visual 2 studio 2017/ MFC

TCHAR szFileName[MAX_PATH + 1];
GetModuleFileName(NULL, szFileName, MAX_PATH + 1);
auto exe = CString(szFileName);

exe contains full path to 1 exe.

Score: 0

According to MSDN:

The global variable _pgmptr is automatically 3 initialized to the full path of the executable 2 file, and can be used to retrieve the full 1 path name of an executable file.

Score: 0

I guess I like to make it a habit to add 10 answers to really old questions. Let's do 9 it again!

The very simplest way to get the 8 current running .exe on a Windows system 7 is to use the SDK defined global variable 6 _pgmptr. However, it's considered "unsafe", so 5 you use _get_pgmptr() instead.

So...

char *exe;
_get_pgmptr(&exe);
std::cout << "This executable is [" << exe << "]." << std::endl;

If you have a "wide" (UTF16) entrypoint, such 4 as wmain or wWinMain, use this instead:

wchar_t* wexe;
_get_wpgmptr(&wexe);
std::wcout << L"This executable is [" << wexe << L"]." << std::endl;

If 3 you really, really insist on using the simpler 2 version, here's how to do it:

#define _CRT_SECURE_NO_WARNINGS 1
#include <iostream>

int main(int argc, char** argv)
{
    std::cout << "This executable is [" << _pgmptr << "]." << std::endl;
}

Just don't 1 get yourself pwned by hax0rs! 🤣

More Related questions