In Delphi code, I'm trying to access a folder on the LAN that is protected with user name and password. It could be inside a Windows PC or a NAS. I'm doing my test on my Windows 10 PC running Delphi 10.2.3. I have created the target folder in another PC on the LAN running Windows Server.
I'm trying with the code that you can see below.
I have two problems:
If I use the path with the computer name (for example:
'\\server-pc\testfolder'), the functionWNetAddConnection2()always returnsERROR_SESSION_CREDENTIAL_CONFLICT.If I use the path with the IP address (for example:
'\\192.168.0.1\testfolder'), the functionWNetAddConnection2()completes successfully and allows my application to access the folder, BUT the functionWNetCancelConnection2()seems to fail: it returnsNO_ERRORBUT the remote folder continues to be available. In Windows Explorer, I can access the folder (I can't before executing the code) and I don't want that. Only my application should be able to access the folder.
Function AddRemoteConnection(RemotePath: String; un, pw: string): word;
var
nr: TNetResource;
r: DWORD;
begin
nr.dwScope := 0;
nr.dwDisplayType := 0;
nr.dwUsage := 0;
nr.dwType := RESOURCETYPE_DISK;
nr.lpLocalName := '';
nr.lpRemoteName := PWideChar(RemotePath);
nr.lpComment := '';
nr.lpProvider := '';
result := WNetAddConnection2(nr, PWideChar(pw), PWideChar(un), 0);
end;
procedure RemoveRemoteConnection(RemotePath: String);
begin
if not(WNetCancelConnection2(PWideChar(RemotePath), 0, True) = NO_ERROR) then
RaiseLastOSError;
end;
procedure TForm8.Button1Click(Sender: TObject);
var
f: TextFile;
r: word;
path, un, pw: string;
begin
path := '\\server-pc\testfolder';
// path:='\\192.168.0.1\testfolder';
un := 'theuser';
pw := 'thepassword';
r := AddRemoteConnection(path, un, pw);
if r = NO_ERROR then
begin
try
assignfile(f, path + '\test.txt');
try
rewrite(f);
writeln(f, 'xxxx');
finally
closefile(f);
end;
finally
RemoveRemoteConnection(path);
end;
end
else
showmessage('error ' + inttostr(r));
end;
I'd like to solve both problems:
- allow to use the computer name in the path.
- disconnect the folder when the task is completed.