1. Computing & Technology

Discuss in my forum

Programmatically Disconnect a Mapped Network Drive

Display "Disconnect Network Drives" or Remove Drive Silently

By , About.com Guide

disconnect network drive from delphi

disconnect network drive from delphi

When working with files and folders in your Delphi applications you might need to provide a user with an option to map a shared network path to a drive letter AND to un-map or disconnect a mapped network location.

Programmatically Execute the Map Network Drive Dialog provides a custom "MapNetworkDrive" function accepts a UNC path and displays the standard Map Network Drive dialog.

This time, we want to remove a network connection from Delphi code...

Programmatically Execute the Disconnect Network Drives Dialog

If you want to programmatically call the Disconnect Network Drives Dialog in your Delphi application, you can do it by calling the WNetDisconnectDialog Windows API function.
 function DisconnectNetworkDriveDialog(const ownerHandle: THandle): boolean;
 begin
   result := WNetDisconnectDialog(ownerHandle, RESOURCETYPE_DISK) = NO_ERROR;
 end;
 
Note: WNetDisconnectDialog returns -1 if the user cancels the dialog box.

Programmatically Remove a Network Drive

If you need to disconnect a mapped network drive silently, without displaying the "disconnect ..." dialog, use the following function:
 //disconnects a network drive
 function DisconnectNetworkDrive(const drive: string; const force, restore, displayError: boolean): DWORD;
 // force: should disconnection occur if there are open files or jobs on the connection
 // restore: should continue to restore the connection at the next logon
 // displayError: show the failure reason if any
 var
   return, dwFlags: DWORD;
 begin
   if restore then
     dwFlags := CONNECT_UPDATE_PROFILE
   else
     dwFlags := 0;
 
   return := WNetCancelConnection2(PChar(drive), dwFlags, force) ;
 
   if (return <> NO_ERROR) and (displayError) then
   begin
     Application.MessageBox(PChar('Could not disconnect, reason:' + #13#10 +
       SysErrorMessage(GetLastError)),
       'DisconnectNetworkDrive',
       MB_OK) ;
   end;
 
   result := return;
 end;
 
Note: SysErrorMessage is used to convert the OS error code into a user friendly message.

Delphi tips navigator:
» Generic Solution to Freeing Objects in Delphi's TStringList Collections
« Programmatically Execute the Map Network Drive Dialog to Map a UNC Path to a Drive Letter Using Delphi

©2012 About.com. All rights reserved.

A part of The New York Times Company.