DelphiFAQ Home Search:
General :: Programming :: Delphi :: Network
Network (local network and Internet) programming under Windows with Delphi.

Articles:

This list is sorted by recent document popularity (not total page views).
New documents will first appear at the bottom.

Featured Article

Map or unmap a network disk at run-time

Question:

I want to attach to a file server and map a network disk from within my Delphi application. How can I do this?

Answer:

You need to use the Windows API function WNetAddConnection2 to map a remote share as a disk.
This function replaces the old WNetAddConnection call which did not allow to specify a username.

If you need to specify a user name or password you can do this in arguments 2 (password) and 3 (user name). Note that example below sends nil. If you send nil as user name and password, then WNetAddConnection2 will use the user context for the running process and the password associated with this account.

Note that supplying a user name/ password other than the process currently running will only work on Windows NT, Windows 2000 and Windows XP.

Finally use WNetCancelConnection2() to remove a network mapping.

uses 
   Windows;
 
 var
   nw: TNetResource;
   errCode : DWord;
 begin
   nw.dwType := RESOURCETYPE_DISK;
   nw.lpLocalName := nil;
   nw.lpRemoteName := PChar('\\the_fileserver\C$');
   nw.lpProvider := nil;
   nw.lpLocalName := 'R:';
   errCode := WNetAddConnection2(nw, {password}nil, {user name}nil, 0);
   if errCode = NO_ERROR then
   begin
     ShowMessage('The disk is mapped as R:');
   end;
 end;

Generated 16:01:19 on May 23, 2018