问题
Hey,
I'm trying to get the path to a dll located in the same folder as my exe file. The way to go seems to be to use one of either QueryFullProcessImageName()
or GetModuleFileName()
to get the path to the running executable and then use string manipulation to make it a path to the required library instead.
Unfortunately, neither of these two functions provide a way to find out in advance the size buffer required. I've tried passing zero in for the nSize parameter, but this doesn't have the desired effect.
What's the best practice way of doing this?
回答1:
In practice you can use Windows API MAX_PATH
as your buffer size, perhaps add 1 for extra safety.
In theory a Windows path can be much larger. As I recall MAX_PATH
is like 270 or thereabouts, while in the NTFS file system a path can be up to around (roughly) 32767 chars. However, for that large size it has to be handled as Unicode, and, importantly, Windows Explorer does not support such large paths, so it's not an issue in practice.
In practice, again, if you should ever encounter such large path, apparently impossible to remove, then you can use the Unicode naming (there's a special prefix to use for long paths), and/or equivalent shortnames (DOS 8.3 names), and/or define logical drives to shorten the path, so that the directory/file can be removed.
Cheers & hth.,
回答2:
GetModuleFilename
returns the number of characters copied to your buffer. If it's less than the size of your buffer, you're fine. If it's equal to the size of your buffer, allocate a larger buffer and try again.
来源:https://stackoverflow.com/questions/4841546/safely-get-path-to-running-executable-in-windows-api