ojx16q
Last Updated: February 15, 2018
·
3.88K
· guionardo

Retrieves the name of the network resource associated with a local device.

When you need to know where the mapped drive points in a network resource, use this function:


using System.Runtime.InteropServices;

        [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]
        public static extern int WNetGetConnection(
            [MarshalAs(UnmanagedType.LPTStr)] string localName,
            [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,
            ref int length);
 public static string GetConnection(string localname)
        {
            var sb = new StringBuilder(512);
            var size = sb.Capacity;
            var error = WNetGetConnection(localname, sb, ref size);
            if (error != 0)
            {
                // Local device is not mapped 
                return "";
            }                
            return sb.ToString();
        }

Use:

Console.WriteLine(GetConnection("L:"));

returns:

\\MY-SERVER\LABORATORY