Network Resources Mapping
var
NetResource : TNetResource;
begin
NetResource.dwType := RESOURCETYPE_DISK;
NetResource.lpLocalName := 'm:'; {use here letters A-Z that are not already mapped}
NetResource.lpRemoteName := '\\computer_name\resource_name';
NetResource.lpProvider := '';
WNetAddConnection2(NetResource, '[password]', '[user]', CONNECT_UPDATE_PROFILE);
end;
For disconnecting the resource:
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;
Or just connect to the resource, no mapping:
function ConnectServer(path: string): boolean;
var
res : TNetResource;
reslt : Cardinal;
begin
if (sUser <> '') and (sPass <> '') then
begin
res.dwType := RESOURCETYPE_DISK;
res.lpLocalName := nil;
res.lpRemoteName := PChar(path);
res.lpProvider := nil;
reslt := WNetAddConnection2(res, PWideChar(sPass),
PChar(sUser), CONNECT_UPDATE_RECENT or CONNECT_TEMPORARY);
if reslt <> NO_ERROR then
begin
WriteLn('Cannot connect to destination server with supplied credentials' + #13#10 + 'Error code = ' + IntToStr(reslt));
WriteLn(' Credentials used were: ' + sUser + ' - ' + sPass);
Result := false;
end
else
Result := true;
end
else
// if empty credentials, consider that connect/disconnect are disabled
Result := true;
end;