Today one of my colleagues was working on piece of code that would turn a given mapped drive to full UNC path. The code to do implement the functionality is very simple and can be done in a variety of ways ranging from Win32 API to WMI (via System.Management) Below is a snippet of the code that was used.

   1: public static string GetUNCPath(string originalPath)
   2: {
   3:     string returnVal = originalPath;
   4:     foreach (DriveInfo drive in System.IO.DriveInfo.GetDrives())
   5:     {
   6:         if (Path.GetPathRoot(originalPath).ToLower().StartsWith(drive.RootDirectory.FullName.ToLower()))
   7:         {
   8:             if (drive.DriveType == DriveType.Network)
   9:             {
  10:                 System.Management.ManagementObjectSearcher searcher = new System.Management.ManagementObjectSearcher(
  11:                     @"\\.\root\cimv2", "Select * From Win32_LogicalDisk Where DriveType = 4");
  12:  
  13:                 foreach (System.Management.ManagementObject obj in searcher.Get())
  14:                 {
  15:                     if (obj["DeviceID"].ToString().ToLower().StartsWith(drive.Name.ToLower().Substring(0, 2)))
  16:                     {
  17:                         returnVal = Path.Combine(obj["ProviderName"].ToString(),
  18:                             originalPath.ToLower().Replace(drive.Name.ToLower(), string.Empty));
  19:                         break;
  20:                     }
  21:                 }
  22:             }
  23:             else if (drive.DriveType == DriveType.Fixed)
  24:             {
  25:                 Console.WriteLine("The drive is not a network drive");
  26:             }
  27:             break;
  28:         }
  29:     }
  30:     return returnVal;
  31: }

 

This code can easily be tested using , a great tool that is pretty much a must have for any developer.  I have attached the code file that can be used with snippet compiler all that you will need to do is to change the mapped path that is passed into the method and  a reference to System.Management.dll in Snippet Compiler. You can then run the code with UAC turned on with Run As Administrator or just a normal use to see the difference.

When running this code on Windows Vista with UAC turned on and Visual Studio 2005 or 2008 in administrator mode will provide different results. While getting different results is the correct behavior, unless you are fully aware of the various areas that running applications in a secondary login has  impact on the notion of running your application in a different user context can cause a lot of wasted hours.

As a general rule when debugging code or running code on a machine that has UAC enabled my advice would be to spend a quick second to check if UAC has a part to play in the puzzle.

Share/Save/Bookmark

, , , , , ,
Trackback

no comment untill now

Add your comment now