Sunday, July 19, 2009

Network Drive Mapping Class

Today my friend asked me a question about how to map to a network share-point as a local logical drive with user name and password. I recalled that I had written a utility class to do that.

Basically this static class contains two methods: MappingDrive() and UnMappingDrive(). The first one is used to map to a network share point by its path, user name and password, as well as a specified local logic drive name. The unmap method just takes one parameter of a mapped drive name.

There are many ways to do that. I saw many people using Windows API method. However, I don't like that. The reason is that 1) API are un-managed codes based on dynamic library dll files; and 2)possible un-catchable exceptions, which are very nasty for applications. To map to a network shared point, it is very possible to pass incorrect parameters. Then I found a simple way to do it: by using .Net Process to shell net.exe, which is one of core Windows utilities. Actually, I have used this many times in cmd console. I think most Windows UI tools, including File Explorer, may rely on this tool to do the job.

When I revisit my codes today, I saw that MappingDrive() method is checking if the specified drive is already mapped or not first. If it is true, it will un-map and remap it again. It is done behind sense. This may un-map other people's mapping. I keep this logic and remind my friend about the logic.

I also updated the class with some changes. First, I expose the previously private method of IsMappedDrive() as public. Secondly, I added two methods: GetLocalDrives() and GetLocalUnusedDrives(). The first one is very simple. It is based on System.IO.Directory.GetLogicalDrives(), but I think the second one is more useful. It will get all the un-used local logical drives, which depends on the first method.

Finally, I uploaded this simple NetworkDrive class to my code project. Enjoy it!