Results 1 to 26 of 26

Thread: [RESOLVED] Get UNC from network mapped drive letter

  1. #1

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Resolved [RESOLVED] Get UNC from network mapped drive letter

    Does anyone have a handy way to get the full UNC (\\servername\) from a network mapped drive (X:\)?

    Every method that I've tried on here and other sites seems to be deprecated.

  2. #2
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Get UNC from network mapped drive letter


  3. #3

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Paul,

    No joy. I modified the code in my class to:

    VB.NET Code:
    1. Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _
    2.              "WNetGetConnectionA" (ByVal lpszLocalName As String,
    3.              ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer
    4.  
    5.     Public Shared Function GetUNCPath(ConnStr As String)
    6.  
    7.         Dim ret As Integer
    8.         Dim out As String = New String(" ", 260)
    9.         Dim len As Integer = 260
    10.  
    11.         ret = WNetGetConnection(ConnStr, out, len)
    12.         If out.Count > 0 Then
    13.             Return out.Trim
    14.             Console.WriteLine("UNC Path:   " & out.Trim)
    15.         Else
    16.             Return String.Empty
    17.             Console.WriteLine("Drive not found")
    18.         End If
    19.         ' Console.WriteLine(out)
    20.         Console.ReadLine()
    21.     End Function

    I'm calling the Function:

    VB.NET Code:
    1. Dim TxtPath As String = Me.TextBox1.Text 'This is L:\Project\Xray
    2.             Dim DirPath As String = GetUNCPath(TxtPath)

    The function is returning String.Empty

  4. #4
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Get UNC from network mapped drive letter

    Try it with TxtPath being just L:/

  5. #5
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: Get UNC from network mapped drive letter

    TxtPath needs to be just L: - as you specify the local device name, not a path.
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  6. #6

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Still not getting anything but String.Empty. I modified the function to resolve the URL down to L:\ like this:

    VB.NET Code:
    1. Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _
    2.              "WNetGetConnectionA" (ByVal lpszLocalName As String,
    3.              ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer
    4.  
    5.     Public Shared Function GetUNCPath(ConnStr As String)
    6.  
    7.         'ConnStr comes in as L:\Project\Xray
    8.         Dim letterOnly As String = ConnStr.Substring(0, 3) 'Resolves to L:\
    9.         Dim ret As Integer
    10.         Dim out As String = New String(" ", 260) 'Not sure what the purpose of this is?
    11.         Dim len As Integer = 260
    12.  
    13.         ret = WNetGetConnection(letterOnly, out, len)
    14.         If out.Count > 0 Then
    15.             Dim UNCPrefix As String = out.Trim         'This is resulting in an empty string??
    16.             Dim UNCPath As String = ConnStr.Substring(3)
    17.             Dim fullPath As String = UNCPrefix & UNCPath
    18.             Return fullPath
    19.             Console.WriteLine("UNC Path:   " & out.Trim)
    20.         Else
    21.             Return String.Empty
    22.             Console.WriteLine("Drive not found")
    23.         End If
    24.         ' Console.WriteLine(out)
    25.         Console.ReadLine()
    26.     End Function

    VB.NET Code:
    1. Dim TxtPath As String = Me.TextBox1.Text 'This is L:\Project\Xray
    2.             Dim DirPath As String = GetUNCPath(TxtPath)

  7. #7

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Deleted post, it was repeated for some reason.
    Last edited by Fedaykin; Aug 5th, 2019 at 10:39 AM. Reason: Repeated post

  8. #8
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: Get UNC from network mapped drive letter

    See my post #5! - Just needs to be L:
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  9. #9
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Get UNC from network mapped drive letter

    Dim letterOnly As String = ConnStr.Substring(0, 2) 'Resolves to L:

  10. #10

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Quote Originally Posted by 2kaud View Post
    TxtPath needs to be just L: - as you specify the local device name, not a path.
    Changing from L:\ to L: still produces a blank string returned:

    VB.NET Code:
    1. Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _
    2.              "WNetGetConnectionA" (ByVal lpszLocalName As String,
    3.              ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer
    4.  
    5.     Public Shared Function GetUNCPath(ConnStr As String)
    6.        
    7.         'ConnStr comes in as L:\Project\Xray
    8.  
    9.         Dim letterOnly As String = ConnStr.Substring(0, 2) 'Resolves to L: (Neither L: or L:\ works)
    10.         Dim ret As Integer
    11.         Dim out As String = New String(" ", 260)
    12.         Dim len As Integer = 260
    13.  
    14.         ret = WNetGetConnection(letterOnly, out, len)
    15.         If out.Count > 0 Then
    16.             Dim UNCPrefix As String = out.Trim                  'This is resulting in an empty string?
    17.             Dim UNCPath As String = ConnStr.Substring(3)
    18.             Dim fullPath As String = UNCPrefix & UNCPath
    19.             Return fullPath
    20.             Console.WriteLine("UNC Path:   " & out.Trim)
    21.         Else
    22.             Return String.Empty
    23.             Console.WriteLine("Drive not found")
    24.         End If
    25.         ' Console.WriteLine(out)
    26.         Console.ReadLine()
    27.     End Function

  11. #11
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: Get UNC from network mapped drive letter

    I'm not a VB programmer, so can't give you vb code. But this c++ code produces the expected output on my computer

    Code:
    #include <winnetwk.h>
    #pragma comment(lib, "mpr")
    
    int main()
    {
    	char szDeviceName[260];
    	DWORD cchBuff = sizeof(szDeviceName);
    
    	switch (WNetGetConnection("z:", szDeviceName, &cchBuff))
    	{
    		//
    		// Print the connection name or process errors.
    		//
    		case NO_ERROR:
    			printf("Connection name: %s\n", szDeviceName);
    			break;
    
    			//
    			// The device is not a redirected device.
    			//
    		case ERROR_NOT_CONNECTED:
    			printf("Device z: not connected.\n");
    			break;
    
    			//
    			// The device is not currently connected, but it is a persistent connection.
    			//
    		case ERROR_CONNECTION_UNAVAIL:
    			printf("Connection unavailable.\n");
    			break;
    
    			//
    			// Handle the error.
    			//
    		default:
    			printf("WNetGetConnection failed.\n");
    	}
    }
    In your VB code, you're not checking the return value for error - so don't know what error is occurring. If you obtain and show the return value of WNetGetConnection() then it might indicate the reason for the problem.

    PS The network drive is not already connected then WNetGetConnection() may fail. In this case you need to first connect to the network drive.
    Last edited by 2kaud; Aug 5th, 2019 at 11:28 AM. Reason: PS
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  12. #12
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Get UNC from network mapped drive letter

    Have you tried setting some break points, and stepping through the code to see what is what? If it's returning an empty string, then it seems like it is failing the if out.count check... so that' where I'd start...
    I don't think .Count does what you think it does... in fact, I'm not even sure why you're using it at all. If you're looking to see if the UNC resolved or not, look at ret ... that should return a value that indicates if it was resolved successfully or not.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  13. #13
    eXtreme Programmer .paul.'s Avatar
    Join Date
    May 2007
    Location
    Chelmsford UK
    Posts
    26,413

    Re: Get UNC from network mapped drive letter

    There's also a possibility the the API might need you to target x86

  14. #14

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Quote Originally Posted by techgnome View Post
    Have you tried setting some break points, and stepping through the code to see what is what? If it's returning an empty string, then it seems like it is failing the if out.count check... so that' where I'd start...
    I don't think .Count does what you think it does... in fact, I'm not even sure why you're using it at all. If you're looking to see if the UNC resolved or not, look at ret ... that should return a value that indicates if it was resolved successfully or not.

    -tg
    I agree, none of this does what I think it should do! I was just using the example code that was referenced by .paul in his original reply. I've tried many of these examples all over the internet, none of them work as intended. II am not married to this method, I'm just searching for ANY method to return the UNC of a mapped drive letter on the users machine. I've set break points on everything.

    Ret returns code 2250 'The network connecton could not be found' according to: https://docs.microsoft.com/en-us/win...nt-error-codes

  15. #15
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Get UNC from network mapped drive letter

    OK, now here's the next thing. Windows made a change at some point, I think it was with Win7, in how and when it does the mapping. It used to be that when you logged into Windows, i would re-connect all mapped drives instantly... or attempt to... but that would cause problems if the resource was off line, or required the user to connect via VPN or something else first. This slowed down the login process for a lot of users. Even when the resource is available, it slows down because it's having to send the login info, and reconnect the drive. They were also finding out that often, just because a drive was mapped, doesn't mean a user was actually going to use it. At my last job, I had some dozen mapped drives, I almost never used them. So what MS did was to delay when the connection happens. It got delayed until the drive was actually requested... then the login info was sent and the connection was made. And that maybe what's happening in this case. The drive isn't actually available because it hasn't been connected to and established yet. Just a guess though...

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  16. #16
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: Get UNC from network mapped drive letter

    Return code 2250 is ERROR_NOT_CONNECTED. ie the network connection does not exist.

    Code:
    //
    // MessageId: ERROR_NOT_CONNECTED
    //
    // MessageText:
    //
    // This network connection does not exist.
    //
    #define ERROR_NOT_CONNECTED              2250L
    Before using WNetGetConnection(), you first need to connect to the device.

    Also from MSDN https://docs.microsoft.com/en-us/win...getconnectiona

    If the network connection was made using the Microsoft LAN Manager network, and the calling application is running in a different logon session than the application that made the connection, a call to the WNetGetConnection function for the associated local device will fail. The function fails with ERROR_NOT_CONNECTED or ERROR_CONNECTION_UNAVAIL. This is because a connection made using Microsoft LAN Manager is visible only to applications running in the same logon session as the application that made the connection. (To prevent the call to WNetGetConnection from failing it is not sufficient for the application to be running in the user account that created the connection.)
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  17. #17

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    I think you're both on to something with the connection not existing. I found this https://social.msdn.microsoft.com/Fo...orum=vbgeneral But of course there is no example of the method I need which I think would be WNetGetUniversalName. Unfortunately I do not understand this InAttribute stuff.

  18. #18

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Well, okay. How so how do I 'wake up' the connection? Doing this on the L: drive returns FALSE:

    VB.net Code:
    1. Dim letterOnly As String = ConnStr.Substring(0, 2)
    2.         Dim driveExists As Boolean = Directory.Exists(letterOnly & ":") 'Tried both L: and L:\, both show FALSE even though my local machine is mapped to the L drive!

  19. #19
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: Get UNC from network mapped drive letter

    An alternative is to execute the cmd "net use L:" (or whatever drive letter is required), send its output to a file and then read and parse the file. This doesn't require the connection to be established as long as it is defined. Sorry, but I can't give you the VB code (as I only use c/c++), but the c++ code is:

    Code:
    int main()
    {
    	system("net use z: > netusez.txt 2> null:");
    
    	if (auto f = fopen("netusez.txt", "r"); f != NULL) {
    		char ln[256];
    
    		fgets(ln, 255, f);
    		fgets(ln, 255, f);
    		if (strncmp(ln, "Remote name", 11) == 0)
    			if (auto r = strchr(ln, '\\'); r != NULL)
    				cout << r << endl;
    			else
    				cout << "Not a valid remote name\n";
    		else
    			cout << "Not a valid drive\n";
    	} else
    		cout << "Problem opening file\n";
    }
    This should be fairly easy to translate into VB by someone who knows VB.
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  20. #20
    PowerPoster techgnome's Avatar
    Join Date
    May 2002
    Posts
    34,687

    Re: Get UNC from network mapped drive letter

    Quote Originally Posted by Fedaykin View Post
    Well, okay. How so how do I 'wake up' the connection? Doing this on the L: drive returns FALSE:

    VB.net Code:
    1. Dim letterOnly As String = ConnStr.Substring(0, 2)
    2.         Dim driveExists As Boolean = Directory.Exists(letterOnly & ":") 'Tried both L: and L:\, both show FALSE even though my local machine is mapped to the L drive!
    Haven't tried it, but from what I remember you have to use it... not just check to see if it exists, but use it... like get the directory listing or something. And it doesn't always wake up on the first attempt either, that it might take 2-3 attempts.

    -tg
    * I don't respond to private (PM) requests for help. It's not conducive to the general learning of others.*
    * I also don't respond to friend requests. Save a few bits and don't bother. I'll just end up rejecting anyways.*
    * How to get EFFECTIVE help: The Hitchhiker's Guide to Getting Help at VBF - Removing eels from your hovercraft *
    * How to Use Parameters * Create Disconnected ADO Recordset Clones * Set your VB6 ActiveX Compatibility * Get rid of those pesky VB Line Numbers * I swear I saved my data, where'd it run off to??? *

  21. #21
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,129

    Re: Get UNC from network mapped drive letter

    try a loop, see if it returns

    Code:
    Imports System.Text
    
    
    Public Class Form2
    
        Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _
                 "WNetGetConnectionA" (ByVal lpszLocalName As String, _
                 ByVal lpszRemoteName As StringBuilder, ByRef cbRemoteName As Integer) As Integer
    
       
    
    
        Private Sub Button1_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles Button1.Click
            For Each drv In IO.DriveInfo.GetDrives()
                If drv.DriveType = IO.DriveType.Network Then
                    Dim UncPath As New System.Text.StringBuilder(255)
                    WNetGetConnection(drv.Name.Replace("\", ""), UncPath, UncPath.Capacity)
                    MessageBox.Show(drv.Name & " maps to " & UncPath.ToString)
                End If
            Next
        End Sub
    End Class

    see this thread http://www.vbforums.com/showthread.p...-network-drive Post#5
    Last edited by ChrisE; Aug 6th, 2019 at 01:12 AM.
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

  22. #22

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: Get UNC from network mapped drive letter

    Any looping or multiple attempts to wake the connection returned false. It's pretty silly to me that .NET does not have a good method to resolve a mapped drive letter to a proper UNC.

    I thank everyone for their input! I was inspired by 2kaud's C++ method, but I opt'd for a simpler call to command prompt NET USE.

    I modified a function that I found on the web for my purpose that works pretty well. It dumps the entire cmd prompt text into a string (no need to write out and read from .txt file!), then I just parse out the Remote Name using Regex:

    VB.net Code:
    1. Public Shared Function GetUNCPath(ConnStr As String)
    2.         Dim UNCPath As String = Nothing
    3.         Dim letterDrive As String = ConnStr.Substring(0, 2) 'Returns  'L:'
    4.         If letterDrive <> "\" Then
    5.             Dim nakedPath As String = ConnStr.Substring(2) 'Returns  '\Folder\folder\file.txt'
    6.             Dim si As ProcessStartInfo = New ProcessStartInfo("cmd.exe")
    7.             si.RedirectStandardInput = True
    8.             si.RedirectStandardOutput = True
    9.             si.UseShellExecute = False
    10.             Dim p As Process = Process.Start(si)
    11.             p.StandardInput.WriteLine("NET USE " & letterDrive)
    12.             p.StandardInput.WriteLine("exit")
    13.             Dim output As String = p.StandardOutput.ReadToEnd()
    14.             Dim UNCPrefix As String = Regex.Match(output, "(?<=Remote name\s{7}).*?(?=\n)").ToString 'Regex grabs string between 'Remote name(+7 spaces)' and a new line in the string.
    15.             Dim RemLineBrk As String = UNCPrefix.Replace(vbCr, "") 'Removes the line break at the end of the string
    16.             UNCPath = RemLineBrk & nakedPath
    17.         ElseIf letterDrive = "\" Then
    18.             UNCPath = ConnStr
    19.         End If
    20.         Return UNCPath
    21.     End Function

    Edit: Added code to handle if the directory path was unmapped (already a full UNC)

    Then call it:
    VB.NET Code:
    1. Dim MappedPath As String = Me.TextBox1.Text
    2. Dim UNCPath As String = GetUNCPath(MappedPath )
    Last edited by Fedaykin; Aug 7th, 2019 at 12:06 PM. Reason: Added code to handle if the UNC path was unmapped

  23. #23
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: [RESOLVED] Get UNC from network mapped drive letter

    I realise this thread is resolved, but after some investigation and for info, there is an easier method of obtaining the UNC from a network mapped drive letter.

    The mapped drive letters are stored as keys (without the : ) under:

    HKEY_CURRENT_USER/Network

    Each mapped drive letter is then a separate key under this (without the : ). The value of RemotePath gives the UNC of the network mapped drive letter.

    This method is obviously easier (and quicker!) than executing NET USE and parsing the output someway.
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  24. #24

    Thread Starter
    Addicted Member
    Join Date
    Jul 2013
    Posts
    178

    Re: [RESOLVED] Get UNC from network mapped drive letter

    Quote Originally Posted by 2kaud View Post
    I realise this thread is resolved, but after some investigation and for info, there is an easier method of obtaining the UNC from a network mapped drive letter.

    The mapped drive letters are stored as keys (without the : ) under:

    HKEY_CURRENT_USER/Network

    Each mapped drive letter is then a separate key under this (without the : ). The value of RemotePath gives the UNC of the network mapped drive letter.

    This method is obviously easier (and quicker!) than executing NET USE and parsing the output someway.
    Wow, nice! What's your VB.net code for reading the registry key?

  25. #25
    Frenzied Member 2kaud's Avatar
    Join Date
    May 2014
    Location
    England
    Posts
    1,169

    Re: [RESOLVED] Get UNC from network mapped drive letter

    Quote Originally Posted by Fedaykin View Post
    Wow, nice! What's your VB.net code for reading the registry key?
    Sorry, but I don't use VB, only c/c++. Perhaps some VB guru could provide this?
    All advice is offered in good faith only. You are ultimately responsible for the effects of your programs and the integrity of the machines they run on. Anything I post, code snippets, advice, etc is licensed as Public Domain https://creativecommons.org/publicdomain/zero/1.0/

    C++23 Compiler: Microsoft VS2022 (17.6.5)

  26. #26
    PowerPoster ChrisE's Avatar
    Join Date
    Jun 2017
    Location
    Frankfurt
    Posts
    3,129

    Re: [RESOLVED] Get UNC from network mapped drive letter

    Quote Originally Posted by Fedaykin View Post
    Wow, nice! What's your VB.net code for reading the registry key?
    turn on google ....https://www.dotnetheaven.com/article...stry-in-vb.net
    to hunt a species to extinction is not logical !
    since 2010 the number of Tigers are rising again in 2016 - 3900 were counted. with Baby Callas it's 3901, my wife and I had 2-3 months the privilege of raising a Baby Tiger.

Tags for this Thread

Posting Permissions

  • You may not post new threads
  • You may not post replies
  • You may not post attachments
  • You may not edit your posts
  •  



Click Here to Expand Forum to Full Width