Monday, February 23, 2009

[VC++] Map or Unmap network drive

Are you looking for a standard 'Map Network Drive' dialog for mapping a network resource as a local drive to your Computer ? Or you may be looking for ‘Disconnect Network Drives' dialog box for disconnecting network resource mapped as your local drive ? Here is how to show such dialogs for mapping or disconnecting network resources using two APIs WNetConnectionDialog() and WNetDisconnectDialog(),

Showing 'Map Network Drive' dialog box

// Show Map Network Drive dialog
DWORD dwNetConnectRes = WNetConnectionDialog( 0, RESOURCETYPE_DISK );
if( NO_ERROR == dwNetConnectRes )
{
// successfully mapped the drive
}
else if( -1 == dwNetConnectRes )
{
// User canceled
}
else
{
// Mapping network drive failed
}
Above code when executed will display the 'Map Network Drive' dialog as shown below. For mapping a network resource press the Browse... button and select the network resource and press Finish.

Showing 'Disconnect Network Drives' dialog box
// Show Disconnect Network Drives dialog
DWORD dwNetDisConnectRes = WNetDisconnectDialog( 0, RESOURCETYPE_DISK );
if( NO_ERROR == dwNetDisConnectRes )
{
// successfully unmapped the drive
}
else if( -1 == dwNetDisConnectRes )
{
// User canceled
}
else
{
// Disconnecting network drive failed
}
See the below Disconnect Drives dialog displayed in my machine(with two network resources mapped already) on executing the above code. To disconect just select and press OK button.
For availing the above APIs you may need to incude header file winnetwk.h and link to mpr.lib.

No comments: