I am trying to convert the local path where the C++ executable is stored to a UNC path using the implementation suggested by Stefan. But I get a 2250 error, which according to Microsoft's Network Management Codes means 'The network connection could not be found'
Does anyone know how I can adapt my code to get the UNC path?
Here is minimal reproducing code.
#include <iostream>
#include <Windows.h>
#include <sstream>
#include <shlwapi.h>
#include <windows.h>
#include <string>
#pragma comment(lib, "netapi32.lib")
#pragma comment(lib, "Shlwapi.lib")
using namespace std;
std::wstring ConvertToUNC(wstring sPath);
std::wstring GetExecutableDirectory()
{
// Get the full path to the executable file
wchar_t buffer[MAX_PATH];
GetModuleFileName(NULL, buffer, MAX_PATH);
// Remove the file name from the path
PathRemoveFileSpec(buffer);
return std::wstring(buffer);
}
int main()
{
std::wstring localPath = GetExecutableDirectory();
std::wstring uncPath = ConvertToUNC(localPath);
wcout << L"Local path: " << localPath << endl;
wcout << L"UNC path: " << uncPath << endl;
return 0;
}
std::wstring int_to_wstring(int i) {
std::wstringstream ss;
ss << i;
return ss.str();
}
wstring ConvertToUNC(wstring sPath)
{
WCHAR temp;
UNIVERSAL_NAME_INFO* puni = NULL;
DWORD bufsize = 0;
wstring sRet = sPath;
// Call WNetGetUniversalName using UNIVERSAL_NAME_INFO_LEVEL option
DWORD result = WNetGetUniversalName(sPath.c_str(), UNIVERSAL_NAME_INFO_LEVEL, (LPVOID)&temp, &bufsize);
if (result == ERROR_MORE_DATA)
{
// Now we have the size required to hold the UNC path
WCHAR* buf = new WCHAR[bufsize + 1];
puni = (UNIVERSAL_NAME_INFO*)buf;
result = WNetGetUniversalName(sPath.c_str(), UNIVERSAL_NAME_INFO_LEVEL, (LPVOID)puni, &bufsize);
if (result == NO_ERROR)
{
sRet = wstring(puni->lpUniversalName);
}
else
{
// Failed to retrieve UNC path
sRet = L"Error retrieving UNC path: " + int_to_wstring(result);
}
delete[] buf;
}
else if (result != NO_ERROR)
{
// Failed to retrieve UNC path
sRet = L"Error retrieving UNC path: " + int_to_wstring(result);
}
return sRet;
}
I use Visual Studio 2022 as my coding environment, and my OS is Windows 11. For context, I am new to this language and still learning.
I've tried several things to troubleshoot (but had no luck), including:
- checking the local path exists (it does, and is found by the sample code)
- checking the sharing permissions within the local path folder
- running the C++ code directly from the executable (instead of the VS2022 debugger)
Thank you in advance.