This web site uses cookies. By using the site you accept the cookie policy.This message is for compliance with the UK ICO law.

Network and Internet
.NET 1.1+

Mapping a Drive Letter Programmatically

Some legacy applications do not permit the use of UNC paths when accessing network folders, instead requiring that a drive letter be mapped. When interacting with such software it may be necessary to map a drive letter and later remove mappings using C#.

Calling WNetAddConnection3

Calling the WNetAddConnection3 function is almost identical to WNetAddConnection2, except for the addition parameter for a window handle. If you are calling the function from directly within a form's class, you can simply pass the form's handle using the Handle property, as in the next sample. If you are calling from any other class you will need to obtain a window handle first.

NETRESOURCE networkResource = new NETRESOURCE();
networkResource.dwType = RESOURCETYPE_DISK;
networkResource.lpLocalName = "Z:";
networkResource.lpRemoteName = @"\\BlackWasp\ImageGallery";
networkResource.lpProvider = null;

uint result = WNetAddConnection3(this.Handle, ref networkResource, null, null, 0);

Removing a Drive Mapping

Once you have finished using a drive letter mapping, you may want to disconnect it. If you do, you can use the WNetCancelConnection2 function of the Windows API. In this case there is only a single reference to be created, as there is no definition that includes passing a window handle.

Referencing WNetCancelConnection2

To declare the WNetCancelConnection2 function, use the following code:

static extern uint WNetCancelConnection2(string lpName, uint dwFlags, bool bForce);

Calling WNetCancelConnection2

The cancel command requires three parameters. The first, "lpName", accepts a string containing the drive letter that you wish to disconnect. The second parameter specifies the flags that modify the operation of the command. Only two options are permitted. Passing zero simply disconnects the drive letter, whereas passing CONNECT_UPDATE_PROFILE also removes the drive mapping from the user's profile so that it will not be reconnected after a reboot.

The final parameter, "bForce", is a Boolean value. Usually this should be false. This prevents the mapping from being removed if it is in use. Setting the parameter to true forces disconnection, possibly causing processes using the drive letter to fail.

The following example permanently cancels the Z: mapping, as long as it is not in use:

uint result = WNetCancelConnection2("Z:", CONNECT_UPDATE_PROFILE, false);
21 September 2008