Accessing Network Drives using UNC Path in C#

No.of Views9023
Bookmarked0 times
Downloads 
Votes0
By  Srikanth Chganti   On  31 May 2010 10:05:26
Tag : CSharp , Miscellaneous
Code gain is another avenue opened up for me to post my articles. I am happy to do this! Though this is my first article I am trying to do the best!
emailbookmarkadd commentsprint

Images in this article missing? We recently lost them in a site migration. We're working to restore these as you read this. Should you need an image in an emergency, please contact us at info@codegain.com

 

Introduction

Code gain is another avenue opened up for me to post my articles. I am happy to do this! Though this is my first article I am trying to do the best!

 

Problem

One of the requirements of the product that I was doing is like this: There will be a screen in a windows based application and it consists of a combo box. 

The combo box should display the network drives of the computer. For those who are less literate about network drives; Network Drives are those locations that are mapped to a drive or folder in another system which can be accessed over network. Usually it is often painful to manually navigate to the network location and access the files there. So windows allow us to create network drives on our machines such that we can access the desired network location with just one single click.

How to create a Network Drive?

The creation of network drives is a very simple process.

Open My Computer --> Select tools from the menu bar--> Select the Map Network Drive option.

This opens a window which has a combo box with the existing network drives and non networking drives. Upon selecting a drive the text box below the drop down list will display the path that the network is mapped to. Once you select the drive letter from the combo box , Enter the Network path in the text box and click Finish. Now you should be able to view the network drives in the my computer screen.

Solution to the Problem

If you have ever worked on .NET you would certainly know how vast the base class library of .NET is. We can do many things with it. Yet, we cannot do everything using just the .NET framework and the BCL. Windows OS( XP,VISTA,WINDOWS 7) uses a special assembly called 'mrp.dll". mpr.dll is a module containing functions that are used to handle communication between the Windows operating system and the installed network providers. This assembly basically takes care of the relation between Drive Name Versus the Network Path. So we use the same .dll to fetch us the information that we need. The assembly should be referred as an external assembly and values should be passed to it.  In order to do this we use the DllImport attribute method to point to the mpr.dll. We must point the Drive letters to the external Dll this should be done with the help of MarshallAs  attribute.

Have a look at the folowing code.

 

public static class Pathing
{
    [DllImport("mpr.dll", CharSet = CharSet.Unicode, SetLastError = true)]public static extern int WNetGetConnection(
        [MarshalAs(UnmanagedType.LPTStr)] string localName,
        [MarshalAs(UnmanagedType.LPTStr)] StringBuilder remoteName,ref int length);/// <summary>/// Given a path, returns the UNC path or the original. (No exceptions/// are raised by this function directly). For example, "P:\2008-02-29"/// might return: "\\networkserver\Shares\Photos\2008-02-09"/// </summary>/// <param name="originalPath">The path to convert to a UNC Path</param>/// <returns>A UNC path. If a network drive letter is specified, the/// drive letter is converted to a UNC or network path. If the/// originalPath cannot be converted, it is returned unchanged.</returns>public static string GetUNCPath(string originalPath)
    {
        StringBuilder sb = new StringBuilder(512);int size = sb.Capacity;// look for the {LETTER}: combination ...if (originalPath.Length > 2 && originalPath[1] == ':')
        {// don't use char.IsLetter here - as that can be misleading// the only valid drive letters are a-z && A-Z.char c = originalPath[0];if ((c >= 'a' && c <= 'z') || (c >= 'A' && c <= 'Z'))
            {int error = WNetGetConnection(originalPath.Substring(0, 2),
                    sb, ref size);if (error == 0)
                {
                    DirectoryInfo dir = new DirectoryInfo(originalPath);string path = Path.GetFullPath(originalPath)
                        .Substring(Path.GetPathRoot(originalPath).Length);return Path.Combine(sb.ToString().TrimEnd(), path);
                }
            }
        }return originalPath;
    }
}

As far as my requirement is considered I have a combo box which is currently used to display all the drives that are there in my computer. Irrespective of whether the drive is a network drive or a local drive the current combo box displays all the drives. My requirement is to only display the network drives that are available there in my system.  How do I do this? Thanks to the .NET framework, the DriveInfo class of the framework allows you to search through all the drives that are available on the machine. All that I needed to do was just, run a foreach loop which looks for the Drives which are of network type.

Have a look at the following code 

DriveInfo[] allDrives = DriveInfo.GetDrives();
foreach (DriveInfo d in allDrives)
{if (d.DriveType == DriveType.Network)
    {
        cmbbxDrive.Items.Add(d.ToString());
    }
}

Doing this will allow me to fetch the only network drives into the combo box. Upon selecting one of the drives the Drive's Letter will be sent as a parameter(LPStr) to the MarshalAs method. The "Mpr.dll" will now do the respective task and returns us the string which is essentially the path of Network Drive and the Folder eg: "\\MyServer\MyFolder".

As per the need one can split the path further and save into Database. Otherwise you can send the one who assigned you the task a message saying "MISSION ACCOMPLISHED".

Thank you reading.

 
Sign Up to vote for this article
 
About Author
 
Srikanth Chganti
Occupation-Software Engineer
Company-Optust Software Solutions
Member Type-Fresh
Location-India
Joined date-31 May 2010
Home Page-
Blog Page-http://taravani.blogspot.com
I am a .NET Developer at Optust Software Solutions. C#, and ASP are my core areas of interest
 
 
Other popularSectionarticles
Comments
By:Sukanta SahaDate Of Posted:11/8/2012 6:08:07 AM
Network drive not access
Thanks a lot for your valuable article. The code is fine for administrator user.But error when run the code by other user.I set the permission (read /write) for other user. But show a error System.IO.DirectoryNotFoundException Please Help Me.
By:AlDate Of Posted:5/27/2012 3:35:52 PM
Consultant
Man, there are so many "solutions" to the problem of finding all mapped drives and most of them (including this one!) are grossly uninformed to assume that DriveInfo.GetDrives() returns mapped drives. TEST YOUR CODE before publishing it!
Leave a Reply
Title:
Display Name:
Email:
(not display in page for the security purphase)
Website:
Message:
Please refresh your screen using Ctrl+F5
If you can't read this number refresh your screen
Please input the anti-spam code that you can read in the image.
^ Scroll to Top