Mega Code Archive

 
Categories / Delphi / LAN Web TCP
 

Programmatically Execute the Map Network Drive Dialog to Map a UNC Path to a Drive Letter Using Delphi

Title: Programmatically Execute the Map Network Drive Dialog to Map a UNC Path to a Drive Letter Using 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. A network path is usually given as a UNC (Universal / Uniform Naming Convention) path: "\\server\path\folder". UNC specifies a common syntax to describe the location of a network resource, such as a shared file, directory, or printer. To manually assign a drive letter for a network path you can execute the "Map Network Drive" dialog from the Windows Explorer. See How To Map a Network Drive in Windows XP Using Windows Explorer. Programmatically Execute the Map Network Drive Dialog If you want to programmatically call the Map Network Drive Dialog in your Delphi application, you can do it by calling the WNetConnectionDialog1 Windows API function. The WNetConnectionDialog1 can be used to display the dialog by spefiying the unc path for the user to map it to a drive letter with an option to reconnect at logon. A custom "MapNetworkDrive" function accepts a UNC path and displays the standard Map Network Drive dialog. The handle parameter specifies the owner of the dialog. function MapNetworkDrive(const handle : THandle; const uncPath : string) : string; //returns mapped drive ("z:") on success //or uncPath on failure / cancel var cds : TConnectDlgStruct; netResource : TNetResource; begin result := uncPath; ZeroMemory(@netResource, SizeOf(TNetResource)) ; netResource.dwType := RESOURCETYPE_DISK; netResource.lpRemoteName := PChar(uncPath) ; cds.cbStructure := SizeOf(TConnectDlgStruct) ; cds.hwndOwner := handle; cds.lpConnRes := @netResource; cds.dwFlags := CONNDLG_PERSIST; if WNetConnectionDialog1(cds) = NO_ERROR then begin result := Chr(-1 + Ord('A') + cds.dwDevNum) + DriveDelim; end; end; Usage: MapNetworkDrive(Application.Handle, '\\server\shared-folder'); If the user cancels the dialog or if the function call is unsuccessful, the function returns the uncPath provided. On success the mapped drive letter is returned by the function. TNetDrive TNetDrive is a non-visual Delphi component that programmatically connects a network path to a drive name: NetDrive.Connect(,,);