Finding the path to dotnet.exe
In my Visual C++ application I want to spawn dotnet.exe
to run my DLL. Now, my installer is correctly configured to detect if the .NET8 runtime is needed and will install it. So I know that it is available.
From my research it seems that this is the expected folder:
%programfiles%\dotnet.\dotnet.exe
I the moment I am using the following code:
CString strPath;
SHGetSpecialFolderPath(nullptr, strPath.GetBuffer(_MAX_PATH), CSIDL_PROGRAM_FILES, FALSE);
strPath.ReleaseBuffer();
if (strPath.Right(1) != L"\\")
strPath += L"\\";
strPath += L"dotnet\\dotnet.exe";
It works fine. But I am not sure about how safe it is to hardcode dotnet\dotnet.exe
like that.In my specific case, I have adjusted my code like this:
CString CMeetingScheduleAssistantApp::GetMSAToolsConsoleAppPath()
{
// Get the Program Files directory
CString programFilesPath;
SHGetSpecialFolderPath(nullptr, programFilesPath.GetBuffer(_MAX_PATH), CSIDL_PROGRAM_FILES, FALSE);
programFilesPath.ReleaseBuffer();
// Ensure trailing backslash
if (programFilesPath.Right(1) != L"\\")
programFilesPath += L"\\";
// Construct the full command line
CString fullCommand;
fullCommand.Format(L"\"%sdotnet\\dotnet.exe\" \"%sMSATools\\MSATools.dll\"",
programFilesPath.GetString(), GetProgramPath().GetString());
return fullCommand;
// return GetProgramPath() + L"MSATools\\MSATools.exe";
}
It works ok, but again, I am using hardcoded values. It has also been alluded to that I should modernize this code to use SHGetKnownFolderPath
.So, this is is what I have now:
CString CMeetingScheduleAssistantApp::GetMSAToolsConsoleAppPath()
{
// Get the Program Files directory
CString programFilesPath;
PWSTR pszPath = nullptr;
if (SUCCEEDED(SHGetKnownFolderPath(FOLDERID_ProgramFiles, 0, nullptr, &pszPath)))
{
programFilesPath = pszPath;
CoTaskMemFree(pszPath);
}
else
{
// Fallback to old method if new one fails
SHGetSpecialFolderPath(nullptr, programFilesPath.GetBuffer(_MAX_PATH), CSIDL_PROGRAM_FILES, FALSE);
programFilesPath.ReleaseBuffer();
}
// Ensure trailing backslash
if (programFilesPath.Right(1) != L"\\")
programFilesPath += L"\\";
// Construct the full command line
CString fullCommand;
fullCommand.Format(L"\"%sdotnet\\dotnet.exe\" \"%sMSATools\\MSATools.dll\"",
programFilesPath.GetString(), GetProgramPath().GetString());
return fullCommand;
// return GetProgramPath() + L"MSATools\\MSATools.exe";
}
Any improvements to this function to make it as robust as needed?