DelphiFAQ Home Search:

Map or unmap a network disk at run-time

 

commentsThis article has not been rated yet. After reading, feel free to leave comments and rate it.

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;

Content-type: text/html

Comments:

2012-11-12, 05:33:37
anonymous from United States  

 

 

NEW: Optional: Register   Login
Email address (not necessary):

Rate as
Hide my email when showing my comment.
Please notify me once a day about new comments on this topic.
Please provide a valid email address if you select this option, or post under a registered account.
 

Show city and country
Show country only
Hide my location
You can mark text as 'quoted' by putting [quote] .. [/quote] around it.
Please type in the code:

Please do not post inappropriate pictures. Inappropriate pictures include pictures of minors and nudity.
The owner of this web site reserves the right to delete such material.

photo Add a picture: