Natzely
Natzely

Reputation: 706

Finding Network Drive from UNC Path

I created a button that grabs the text contents of the Clipboard class, checks if it's a folder path and creates a hyperlink out of it. The user will probably just copy the path from the explorer window. The problem I have, which seems to be the opposite of a lot of questions I found, is that I want the drive path (T:\Natzely) instead of the UNC path (\SEOMAFIL02\Trash\Natzely).

When I ctrl+v the copied path into either Word, Notepad or Outlook it gets copied as drive path, but when I copy it to Chrome's address bar or try to retrieve it from the Clipboard class it gets copied as the UNC path. How does Microsoft deal with this?

My drive letters stay pretty much static, so I don't have to worry about the T drive not being the Trash drive in the future.

EDIT

Here is the code

object clipboardText = Clipboard.GetText();
if(!Directory.Exists(clipboardText.ToString()))
{
    //Show error message
}

doc = GetDoc(); //Get document to add the hyperlink to
sel = doc.Selection;
range = sel.Range;
hyperlinks = sel.Hyperlinks;
hyperlinks.Add(range, ref clipboardText);

EDIT Numero Dos

It seems to be more of an issue with Hyperlinks.Add than the clipboard. If I add a space before the clipboard text object clipboardText = " " + Clipboard.GetText() it seems to correct the issue, the hyperlink will now have and extra space before but the link still works.

Upvotes: 2

Views: 1807

Answers (1)

Caleb Mauer
Caleb Mauer

Reputation: 672

Have you see this question from Microsoft? Translate UNC path to local mounted driveletter.

Seems like there are two ways. The first way is to get the value from the registry:

string UNCtoMappedDrive(string uncPath)
{
    Microsoft.Win32.RegistryKey rootKey = Microsoft.Win32.Registry.CurrentUser.OpenSubKey("network");

    foreach (string subKey in rootKey.GetSubKeyNames())
    {
        Microsoft.Win32.RegistryKey mappedDriveKey = rootKey.OpenSubKey(subKey);

        if (string.Compare((string)mappedDriveKey.GetValue("RemotePath", ""), uncPath, true) == 0)
            return subKey.ToUpperInvariant() + @":\";
    }

    return uncPath;
}

The other way is with System.Management. The example is large, but here's the core of it:

private void LoadDrives()
{
    ManagementObjectSearcher searcher = new ManagementObjectSearcher("SELECT RemoteName, LocalName FROM Win32_NetworkConnection");
    List<UncToDrive> drives = new List<UncToDrive>();
    foreach (ManagementObject obj in searcher.Get())
    {
        object localObj = obj["LocalName"];
        if (!Object.Equals(localObj, null))
            drives.Add(new UncToDrive(obj["RemoteName"].ToString(), localObj.ToString()));
    }
}

They search for all paths with the drive (LocalName) and without (RemoteName), then save them in a list for later lookup.

Upvotes: 2

Related Questions