Trying to access a protected shared folder in the LAN in a Delphi application

122 Views Asked by At

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:

  1. If I use the path with the computer name (for example: '\\server-pc\testfolder'), the function WNetAddConnection2() always returns ERROR_SESSION_CREDENTIAL_CONFLICT.

  2. If I use the path with the IP address (for example: '\\192.168.0.1\testfolder'), the function WNetAddConnection2() completes successfully and allows my application to access the folder, BUT the function WNetCancelConnection2() seems to fail: it returns NO_ERROR BUT 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:

  1. allow to use the computer name in the path.
  2. disconnect the folder when the task is completed.
0

There are 0 best solutions below