尝试在Delphi应用程序中访问LAN中受保护的共享文件夹

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

提问人:Roberto Nicchi 提问时间:9/15/2023 最后编辑:Remy LebeauRoberto Nicchi 更新时间:9/16/2023 访问量:73

问:

在Delphi代码中,我尝试访问LAN上受用户名和密码保护的文件夹。它可能位于 Windows PC 或 NAS 中。我正在运行 Delphi 10.2.3 的 Windows 10 PC 上进行测试。我已经在运行 Windows Server 的 LAN 上的另一台 PC 中创建了目标文件夹。

我正在尝试使用您可以在下面看到的代码。

我有两个问题:

  1. 如果我使用带有计算机名称的路径(例如: ),该函数始终返回 .'\\server-pc\testfolder'WNetAddConnection2()ERROR_SESSION_CREDENTIAL_CONFLICT

  2. 如果我使用带有 IP 地址的路径(例如:),该函数将成功完成并允许我的应用程序访问该文件夹,但该函数似乎失败了:它返回 BUT 远程文件夹仍然可用。在 Windows 资源管理器中,我可以访问该文件夹(在执行代码之前我不能),我不想这样做。只有我的应用程序才能访问该文件夹。'\\192.168.0.1\testfolder'WNetAddConnection2()WNetCancelConnection2()NO_ERROR

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;

我想解决这两个问题:

  1. 允许在路径中使用计算机名称。
  2. 任务完成后断开文件夹连接。
Delphi 目录 共享 局域网

评论

2赞 Remy Lebeau 9/16/2023
"只有我的应用程序才能访问该文件夹“ - 打开连接后,无法阻止同一用户会话中的其他应用程序使用该连接,直到取消连接。但是,您应该考虑将该标志添加到您的呼叫中。CONNECT_TEMPORARYWNetAddConnection2()
0赞 Roberto Nicchi 9/27/2023
您好,我现在的问题是函数 WNetCancelConnection2 返回NO_ERROR但与共享文件夹的连接似乎保持活动状态。我已将CONNECT_TEMPORARY标志添加到 AddConnection 函数中。

答: 暂无答案