Showing posts with label Drive. Show all posts
Showing posts with label Drive. Show all posts

Thursday, December 8, 2011

Map Network Drive using C# / Vb.net code

This post will show you an easier way to map a network drive using dot net code. you are free to use any .net language of your choice. I will be mostly sticking to C# though.

We will be relying on COM Interop for this and we will be referencing the Windows Script Host Object Model for this task. Lets get going....

  • Step 1.
Open your choice of application project. In this case I am opening a new Windows Forms Application in C#. And you are there on the default form :Form1.

  • Step 2.
Add a new reference.
In Solution Explorer, right click on References and Click on Add reference.

Select the COM tab.

Scroll down and select Windows Script Host Object Model
Now the solution explorer will look like this with an IWshRuntimeLibrary added.

Now you are ready to go.

  • Step 3.
Write Code.
Go to the code window. select your required event [button click or form load or just anything].
Create an instance of the class IWshNetwork_Class
Call the MapNetworkDrive method and you are done.

  • Sample Code
IWshNetwork_Class network = new IWshNetwork_Class();
network.MapNetworkDrive("k:",@"\\192.168.20.35\MyShare", Type.Missing, "user1", "password1");

you can use the following code to UnMap or remove the mapping.

network.RemoveNetworkDrive("k:");

Hope this saves some time for you....
Happy Programming...