6

I am working on a application in VC++ where network drives are used to access files. The drives are assigned manually by the users and then select the drive in the application. This results in drives not always being mapped to the same servers.

How would I go about obtaining the UNC path to such a file? This is mostly for identification purposes.

Paradoxyde
  • 757
  • 2
  • 10
  • 15
  • 1
    Do you mean that some user has mapped a network drive `X:\some\file` on a server `\\some-server\some\root` and you want to figure out the UNC path to the original server like: `\\some-server\\some\root\some\file`? – André Caron Feb 10 '12 at 19:26
  • Oui monsieur Caron, that is exactly what I mean. – Paradoxyde Feb 10 '12 at 19:29
  • 1
    See here - http://stackoverflow.com/questions/2067075/how-do-i-determine-a-mapped-drives-actual-path – JSacksteder Feb 10 '12 at 20:22
  • Unfortunately, this example uses .NET, which is not my case. – Paradoxyde Feb 10 '12 at 20:34
  • 1
    @Paradoxyde: the example uses the Win32API using .NET syntax. You can probably come up with a direct translation by removing the marshalling cruft. – André Caron Feb 10 '12 at 21:28

2 Answers2

8

here's the function I use to convert a normal path to an UNC path:

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
    if (WNetGetUniversalName(sPath.c_str(),
        UNIVERSAL_NAME_INFO_LEVEL,
        (LPVOID) &temp,
        &bufsize) == 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;
        if (WNetGetUniversalName(sPath.c_str(),
            UNIVERSAL_NAME_INFO_LEVEL,
            (LPVOID) puni,
            &bufsize) == NO_ERROR)
        {
            sRet = wstring(puni->lpUniversalName);
        }
        delete [] buf;
    }

    return sRet;;
} 
Stefan
  • 43,293
  • 10
  • 75
  • 117
1

Suggest you use WNetGetConnection.

API description is here: http://msdn.microsoft.com/en-us/library/windows/desktop/aa385453(v=vs.85).aspx

Joseph Willcoxson
  • 5,853
  • 1
  • 15
  • 29