method
method

Reputation: 1389

How Do I Get The Current Executing Assembly's Path

I don't know how to explain this but I will try. Here is what I'm using :

C++ :

extern "C" __declspec(dllexport) void c(char path[])
{
    //some code with the path.
}    

C#:

[DllImport("DLL")]
static extern void c(char[] path);

As you can see I'm using an exported function from c++. My question is, is there an easier way to get the path of the application from the DLL without passing it as a parameter to the exported function ?

Upvotes: 2

Views: 4597

Answers (3)

Vince
Vince

Reputation: 399

@peachykeen (who has a most excellent name) is right on with the GetModuleFileName suggestion. The trick to get the EXE path is to pass NULL as the hModule parameter.

From MSDN:

hModule [in, optional] A handle to the loaded module whose path is being requested. If this parameter is NULL, GetModuleFileName retrieves the path of the executable file of the current process.

Upvotes: 2

ssube
ssube

Reputation: 48277

This is really easy, but takes some forethought:

The first thing to do is implement a DllMain in the native DLL, which will cache the module's handle when the DLL loads. That looks like:

EXTERN_C BOOL WINAPI DllMain(_In_ HINSTANCE hinstDLL, _In_ DWORD fdwReason, _In_opt_ LPVOID lpvReserved)
{
    UNREFERENCED_PARAMETER(lpvReserved);

    if (fdwReason == DLL_PROCESS_ATTACH)
    {
        DisableThreadLibraryCalls(hinstDLL);

        g_Handle = hinstDLL;
    }

    return TRUE;
}   

Later, when you want to get the name, just call GetModuleFileName, like so:

TCHAR dllName[MAX_PATH + 1];
GetModuleFileName(g_Handle, dllName, MAX_PATH);

The only complicated part, if you want to call it that, is storing the handle from DllMain. Calling GetModuleHandle(NULL) will give you the executing module's handle, not the DLL (same as GetExecutingAssembly in C#).

Upvotes: 2

Manuel
Manuel

Reputation: 2213

Path for standalone application and windows service(but not for websites):

AppDomain.CurrentDomain.BaseDirectory

Upvotes: 0

Related Questions