|
-
Aug 2nd, 2019, 05:25 PM
#1
Thread Starter
Addicted Member
[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.
-
Aug 2nd, 2019, 06:55 PM
#2
Re: Get UNC from network mapped drive letter
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Aug 5th, 2019, 10:00 AM
#3
Thread Starter
Addicted Member
Re: Get UNC from network mapped drive letter
Paul,
No joy. I modified the code in my class to:
VB.NET Code:
Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _
"WNetGetConnectionA" (ByVal lpszLocalName As String,
ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer
Public Shared Function GetUNCPath(ConnStr As String)
Dim ret As Integer
Dim out As String = New String(" ", 260)
Dim len As Integer = 260
ret = WNetGetConnection(ConnStr, out, len)
If out.Count > 0 Then
Return out.Trim
Console.WriteLine("UNC Path: " & out.Trim)
Else
Return String.Empty
Console.WriteLine("Drive not found")
End If
' Console.WriteLine(out)
Console.ReadLine()
End Function
I'm calling the Function:
VB.NET Code:
Dim TxtPath As String = Me.TextBox1.Text 'This is L:\Project\Xray
Dim DirPath As String = GetUNCPath(TxtPath)
The function is returning String.Empty
-
Aug 5th, 2019, 10:15 AM
#4
Re: Get UNC from network mapped drive letter
Try it with TxtPath being just L:/
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Aug 5th, 2019, 10:24 AM
#5
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)
-
Aug 5th, 2019, 10:36 AM
#6
Thread Starter
Addicted Member
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:
Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _ "WNetGetConnectionA" (ByVal lpszLocalName As String, ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer Public Shared Function GetUNCPath(ConnStr As String) 'ConnStr comes in as L:\Project\Xray Dim letterOnly As String = ConnStr.Substring(0, 3) 'Resolves to L:\ Dim ret As Integer Dim out As String = New String(" ", 260) 'Not sure what the purpose of this is? Dim len As Integer = 260 ret = WNetGetConnection(letterOnly, out, len) If out.Count > 0 Then Dim UNCPrefix As String = out.Trim 'This is resulting in an empty string?? Dim UNCPath As String = ConnStr.Substring(3) Dim fullPath As String = UNCPrefix & UNCPath Return fullPath Console.WriteLine("UNC Path: " & out.Trim) Else Return String.Empty Console.WriteLine("Drive not found") End If ' Console.WriteLine(out) Console.ReadLine() End Function
VB.NET Code:
Dim TxtPath As String = Me.TextBox1.Text 'This is L:\Project\Xray Dim DirPath As String = GetUNCPath(TxtPath)
-
Aug 5th, 2019, 10:37 AM
#7
Thread Starter
Addicted Member
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
-
Aug 5th, 2019, 10:43 AM
#8
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)
-
Aug 5th, 2019, 10:43 AM
#9
Re: Get UNC from network mapped drive letter
Dim letterOnly As String = ConnStr.Substring(0, 2) 'Resolves to L:
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Aug 5th, 2019, 10:45 AM
#10
Thread Starter
Addicted Member
Re: Get UNC from network mapped drive letter
 Originally Posted by 2kaud
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:
Public Declare Function WNetGetConnection Lib "mpr.dll" Alias _ "WNetGetConnectionA" (ByVal lpszLocalName As String, ByVal lpszRemoteName As String, ByRef cbRemoteName As Integer) As Integer Public Shared Function GetUNCPath(ConnStr As String) 'ConnStr comes in as L:\Project\Xray Dim letterOnly As String = ConnStr.Substring(0, 2) 'Resolves to L: (Neither L: or L:\ works) Dim ret As Integer Dim out As String = New String(" ", 260) Dim len As Integer = 260 ret = WNetGetConnection(letterOnly, out, len) If out.Count > 0 Then Dim UNCPrefix As String = out.Trim 'This is resulting in an empty string? Dim UNCPath As String = ConnStr.Substring(3) Dim fullPath As String = UNCPrefix & UNCPath Return fullPath Console.WriteLine("UNC Path: " & out.Trim) Else Return String.Empty Console.WriteLine("Drive not found") End If ' Console.WriteLine(out) Console.ReadLine() End Function
-
Aug 5th, 2019, 11:16 AM
#11
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)
-
Aug 5th, 2019, 11:17 AM
#12
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
-
Aug 5th, 2019, 11:22 AM
#13
Re: Get UNC from network mapped drive letter
There's also a possibility the the API might need you to target x86
- Coding Examples:
- Features:
- Online Games:
- Compiled Games:
-
Aug 5th, 2019, 11:47 AM
#14
Thread Starter
Addicted Member
Re: Get UNC from network mapped drive letter
 Originally Posted by techgnome
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
-
Aug 5th, 2019, 11:58 AM
#15
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
-
Aug 5th, 2019, 12:00 PM
#16
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)
-
Aug 5th, 2019, 01:55 PM
#17
Thread Starter
Addicted Member
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.
-
Aug 5th, 2019, 02:06 PM
#18
Thread Starter
Addicted Member
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:
Dim letterOnly As String = ConnStr.Substring(0, 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!
-
Aug 5th, 2019, 02:18 PM
#19
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)
-
Aug 5th, 2019, 02:40 PM
#20
Re: Get UNC from network mapped drive letter
 Originally Posted by Fedaykin
Well, okay. How so how do I 'wake up' the connection? Doing this on the L: drive returns FALSE:
VB.net Code:
Dim letterOnly As String = ConnStr.Substring(0, 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
-
Aug 6th, 2019, 12:58 AM
#21
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.
-
Aug 6th, 2019, 11:36 AM
#22
Thread Starter
Addicted Member
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:
Public Shared Function GetUNCPath(ConnStr As String) Dim UNCPath As String = Nothing Dim letterDrive As String = ConnStr.Substring(0, 2) 'Returns 'L:' If letterDrive <> "\" Then Dim nakedPath As String = ConnStr.Substring(2) 'Returns '\Folder\folder\file.txt' Dim si As ProcessStartInfo = New ProcessStartInfo("cmd.exe") si.RedirectStandardInput = True si.RedirectStandardOutput = True si.UseShellExecute = False Dim p As Process = Process.Start(si) p.StandardInput.WriteLine("NET USE " & letterDrive) p.StandardInput.WriteLine("exit") Dim output As String = p.StandardOutput.ReadToEnd() 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. Dim RemLineBrk As String = UNCPrefix.Replace(vbCr, "") 'Removes the line break at the end of the string UNCPath = RemLineBrk & nakedPath ElseIf letterDrive = "\" Then UNCPath = ConnStr End If Return UNCPath End Function
Edit: Added code to handle if the directory path was unmapped (already a full UNC)
Then call it:
VB.NET Code:
Dim MappedPath As String = Me.TextBox1.Text 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
-
Aug 17th, 2019, 05:03 AM
#23
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)
-
Aug 19th, 2019, 03:14 PM
#24
Thread Starter
Addicted Member
Re: [RESOLVED] Get UNC from network mapped drive letter
 Originally Posted by 2kaud
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?
-
Aug 20th, 2019, 03:12 AM
#25
Re: [RESOLVED] Get UNC from network mapped drive letter
 Originally Posted by Fedaykin
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)
-
Aug 20th, 2019, 03:28 AM
#26
Re: [RESOLVED] Get UNC from network mapped drive letter
 Originally Posted by Fedaykin
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
-
Forum Rules
|
Click Here to Expand Forum to Full Width
|