Uncovering UNC Paths in .Net

23. December 2009 Uncategorized 0

Today, at my real job, I came across the need to upload some files from a .Net app to a central server.  These are files the users will choose to include in some quotes they generate.  That means there will probably be a network share to hold a collection of these files and the end users will open that share and pick & choose what files they want.

So after perfecting the ability to upload a file from my C:Temp folder, I moved on to the next case, of pulling one from my Z: folder.  As I was quickly reminded, .Net doesn’t like pulling files from mapped drives, it prefers UNC paths.  The problem was, we have several shares are several different servers, so managing the UNCs was outside the scope of the program.

At first, I’d hoped that .Net would handle this for me in some form of System.IO class.  Like System.IO.Drives or something similar.  Unfortunately, it doesn’t.  But it does expose a rather powerful querying mechanism to get information like this (as well as network info etc).

Here’s a code snippet of what I used:

ManagementPath path = new ManagementPath(@"\" + System.Environment.MachineName + @"rootcimv2");
ObjectQuery query = new ObjectQuery("select * from Win32_LogicalDisk WHERE DriveType = 4");
ManagementScope scope = new ManagementScope(path, new ConnectionOptions());
ManagementObjectSearcher search = new ManagementObjectSearcher(scope, query);

foreach (ManagementObject o in search.Get())

Couple notes, first, DriveType 4 is for Mapped Network drives.  Secondly, the Options class can be used if you need to impersonate an admin.  For my application, I didn’t need to do any impersonation, so I just passed an empty Options object.

The output looked something like:


palelocustblogsharebubbas big files

So collecting this information will allow me to substitute the UNC path for the drive letter when needed.