After changing the executable name while the application is running, both GetModuleFileName
and GetModuleFileNameEx
using PID return the original file name.
How can I get the new file name or even detect the change? Ideally I would prefer not to use FindFirstChangeNotification
.
Use QueryFullProcessImageName.
I have met the same problem, and tried GetModuleFileName, GetProcessImageFileName and QueryFullProcessImageName. The last one can work.
This is a simple demo I wrote.
#include <Windows.h>
#include <Psapi.h>
#include <stdio.h>
#pragma comment(lib, "Psapi.lib")
void OutputSelfpath()
{
char szFile[MAX_PATH] = {0};
GetModuleFileName(NULL, szFile, MAX_PATH);
printf("GetModuleFileName:\n\r%s\n\n", szFile);
memset(szFile, 0, MAX_PATH);
HANDLE hProcess = OpenProcess(PROCESS_ALL_ACCESS, FALSE, GetCurrentProcessId());
if (!hProcess)
{
printf("OpenProcess failed!\n");
}
else
{
DWORD dwRet = GetProcessImageFileName(hProcess, szFile, MAX_PATH);
if (dwRet)
{
printf("GetProcessImageFileName:\n\r%s\n\n", szFile);
}
else
{
printf("GetProcessImageFileName failed!\n");
}
memset(szFile, 0, MAX_PATH);
DWORD dwSize = MAX_PATH;
if (QueryFullProcessImageName(hProcess, 0, szFile, &dwSize))
{
printf("QueryFullProcessImageName:\n\r%s\n\n", szFile);
}
else
{
printf("QueryFullProcessImageName failed\n", szFile);
}
}
}
int main()
{
const char* pszFile = "ConsoleTest.exe";
const char* pszNewFile = "ConsoleTest_bak.exe";
remove(pszNewFile);
OutputSelfpath();
int nRet = rename(pszFile, pszNewFile);
if (0 != nRet)
{
printf("rename file failed!\n");
}
else
{
printf("################### after rename ###################\n\n");
OutputSelfpath();
}
system("pause");
return 0;
}
result:
GetModuleFileName:
E:\own-sources\ConsoleTest\Debug\ConsoleTest.exe
GetProcessImageFileName:
\Device\HarddiskVolume3\own-sources\ConsoleTest\Debug\ConsoleTest.exe
QueryFullProcessImageName:
E:\own-sources\ConsoleTest\Debug\ConsoleTest.exe
################### after rename ###################
GetModuleFileName:
E:\own-sources\ConsoleTest\Debug\ConsoleTest.exe
GetProcessImageFileName:
\Device\HarddiskVolume3\own-sources\ConsoleTest\Debug\ConsoleTest.exe
QueryFullProcessImageName:
E:\own-sources\ConsoleTest\Debug\ConsoleTest_bak.exe
I have wrote a blog post about this, see here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With