C# : Get The Full UNC Path Using The Mapped Drive Path On Your Machine.

We generally map network paths as local drives for ease of access and without having to manually go to the shared location. At times, there is a need to  resolve the external network path that has been locally mapped to your machine.

Say you have a shared folder across the network that reads something like \\S734410-W10\shared\tools.

This is mapped to the drive Y:\ on your local workstation. Assume there is a folder named “software” in the mapped location. Ideally, it would read as \S734410-W10\shared\tools\software.

 

However, when you try to access it via some C# code you would always end up getting Y:\software which wouldn’t be understood if the path is being saved universally across systems, maybe in a database.

There is a need to get the UNC ( Universal Naming Convention  ) path from the mapped path and there is no direct code in managed C# that you could find to get this done. The Windows function – WnetGetConnection(…) can be used here to transform the mapped path to UNC path.

public static extern int WNetGetConnection(
[MarshalAs(UnmanagedType.LPTStr)] string localName, 
[MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName, 
ref int length);

The above code block shows the WnetGetConnection(…) function signature.

First parameter localName stands for the mapped path and the second parameter remoteName is a StringBuilder object which gets populated with the resolved path that is represented by the mapped path driver letter ( “Y” in our case ). The third parameter length specified the capacity of the SringBuilder object.

So the method call would be something like this :

int error = WNetGetConnection("Y", sb, 512);

//Y is the mapped drive letter
//sb is the StringBuilder object that will be returned with the resolved path.
//512 is the specified capacity of the StringBuilder object.

 

2 thoughts on “C# : Get The Full UNC Path Using The Mapped Drive Path On Your Machine.

  • Thanks for this article, it was a good starting point.

    Unfortunately you forgot to add the [DllImport] line, which needs to explicitly specify CharSet.Ansi to select the WNetGetConnectionA method that matches the data types in your method signature.

    After some trouble shooting I found a working solution:

    [DllImport(“mpr.dll”, CharSet=CharSet.Auto)]
    public static extern int WNetGetConnection(string localName, StringBuilder remoteName, ref int length);

Leave a Reply

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.