获取可执行文件exe的路径,可以解决获得uwp沙盒的路径的问题

参考的这个路径,

https://stackoverflow.com/questions/41413534/get-app-path-for-fopen-in-uwp?tdsourcetag=s_pcqq_aiomsg

#include "pch.h"
#include <windows.h>
#include <string>

extern "C" IMAGE_DOS_HEADER __ImageBase;

std::wstring GetExecutablePath()
{
	std::wstring buffer;
	size_t nextBufferLength = MAX_PATH;

	for (;;)
	{
		buffer.resize(nextBufferLength);
		nextBufferLength *= 2;

		SetLastError(ERROR_SUCCESS);

		auto pathLength = GetModuleFileName(reinterpret_cast<HMODULE>(&__ImageBase), &buffer[0], static_cast<DWORD>(buffer.length()));

		if (pathLength == 0)
			throw std::exception("GetModuleFileName failed"); // You can call GetLastError() to get more info here

		if (GetLastError() != ERROR_INSUFFICIENT_BUFFER)
		{
			buffer.resize(pathLength);
			return buffer;
		}
	}
}

void RemoveLastPathComponent(std::wstring& path)
{
	auto directoryLength = path.length() - 1;

	while (directoryLength > 0 && path[directoryLength] != '\\' && path[directoryLength] != '/')
		directoryLength--;

	if (directoryLength > 0)
		path.resize(directoryLength);
}

std::wstring GetExecutableDirectory()
{
	auto executablePath = GetExecutablePath();
	RemoveLastPathComponent(executablePath);
	return executablePath;
}

猜你喜欢

转载自blog.csdn.net/whunamikey/article/details/89026069