开发者

Copy file from shared directory with given user name and password

开发者 https://www.devze.com 2023-04-08 05:47 出处:网络
Is there a way to create/copy a file to/from specific network shared directory with different than current user name and开发者_StackOverflow社区 password ?Here\'s what I use to connect and map a remot

Is there a way to create/copy a file to/from specific network shared directory with different than current user name and开发者_StackOverflow社区 password ?


Here's what I use to connect and map a remote drive to a local drive letter (along with the corresponding unmapping operation). Once you've mapped the drive to a drive letter, you copy just like you would with any other drive:

function MapNetworkDrive(const RemoteName, LocalDrive, 
  UserName, Password: string): Boolean;
var
  NetRes: TNetResource;
  Res: DWord;
begin
  Result := True;
  FillChar(NetRes, SizeOf(TNetResource), 0);
  NetRes.dwType := RESOURCETYPE_DISK;
  NetRes.lpRemoteName := PChar(RemoteName);
  NetRes.lpLocalName := PChar(LocalDrive);
  Res := WNetAddConnection2(NetRes, PChar(Password), PChar(UserName), 0);
  Result := (Res = NO_ERROR);
  if not Result then
    SysErrorMessage(Res);
end;

function TForm1.UnmapNetworkDrive(const LocalDrive: string): Boolean;
var
  Res: DWord;
begin
  Res := WNetCancelConnection2(PChar(LocalDrive), 0, True);
  Result := (Res = NO_ERROR);
end;

Example use:

begin
  if MapNetworkDrive('\\192.168.1.56\C$', 'H:', 'fred', 'password') then
  begin
    try
      // Do whatever between local drive and drive 'H:'
    finally
      UnmapNetworkDrive(Local);
    end;
  end;
end;


Either what @Luke suggested in a comment, or you can PInvoke to NetUseAdd function. You can pass user name and password in a call to NetUseAdd and then all attempts from current user session to access resources on this file share will use those credentials. See example on pinvoke.net on how to call it -- you will have to translate this to Delphi.


Alternately you could use the Windows API CreateProcessWithLogon() (Link to MSDN).

0

精彩评论

暂无评论...
验证码 换一张
取 消

关注公众号