2

I have a map drive at location Z:\ which is mapped to \\server1\shared
Now my executable located at \\server1\shared\exe\myExec.exe

I have tried

Directory.GetCurrentDirectory();
Environment.CurrentDirectory;
Path.GetDirectoryName(Assembly.GetExecutingAssembly().Location);
System.AppDomain.CurrentDomain.BaseDirectory

All of them return "\\server1\shared\exe"

Is there a way I can get a result to be "Z:\exe\" ?

TLJ
  • 4,525
  • 2
  • 31
  • 46

1 Answers1

0

I ended up with these 2 functions.

UNC2LocalPath takes UNC Path and return local path. It iterates thru all drives that being map at the local machine. If found a match, it replace server name with the drive letter.

Required reference: System.Management.dll

using System.Management;

public static String UNC2LocalPath(String input)
{
    DriveInfo[] dis = DriveInfo.GetDrives();
    foreach (DriveInfo di in dis)
    {
        if (di.DriveType == DriveType.Network)
        {
            DirectoryInfo dir = di.RootDirectory;
            var unc = GetUNCPath(dir.FullName.Substring(0, 2));
            if (input.StartsWith(unc_path, StringComparison.OrdinalIgnoreCase))
            {
                return input.Replace(Path.GetPathRoot(unc) + "\\", dir.FullName);
            }
        }                
    }
    return null;
}

public static string GetUNCPath(string path)
{
    if (path.StartsWith(@"\\"))
        return path;

    ManagementObject mo = new ManagementObject();
    mo.Path = new ManagementPath(string.Format("Win32_LogicalDisk='{0}'", path));

    //DriveType 4 = Network Drive
    if (Convert.ToUInt32(mo["DriveType"]) == 4)
        return Convert.ToString(mo["ProviderName"]);
    else return path;
}

The function GetUNCPath is taken from ibram's answer @ How do I determine a mapped drive's actual path?

Community
  • 1
  • 1
TLJ
  • 4,525
  • 2
  • 31
  • 46