Delphi 访问并打开局域网共享文件夹

这篇博客介绍了如何使用Delphi程序连接到局域网中的共享文件夹,通过WnetAddConnection2函数建立连接,并进行文件的复制操作。接着,展示了如何断开连接,以及使用ShellExecute打开共享文件夹。对于需要在Delphi中处理网络文件操作的开发者来说,这是一个实用的示例。
unit Unit1;


interface


uses
  Windows, Messages, SysUtils, Variants, Classes, Graphics, Controls, Forms,
  Dialogs, StdCtrls, ShellAPI;


type
  TForm1 = class(TForm)
    Button1: TButton;
    Button2: TButton;
    procedure Button1Click(Sender: TObject);
    procedure ConnectServer;
    procedure DisConnectServer;
    procedure Button2Click(Sender: TObject);
  private
    { Private declarations }
  public
    { Public declarations }
    g_bFlag:boolean;
  end;


var
  Form1: TForm1;


implementation


{$R *.dfm}


procedure TForm1.Button1Click(Sender: TObject);
begin
  ConnectServer;
end;


procedure TForm1.ConnectServer;
var
    NetSource   :   TNetResource;
    dwResult:DWORD;
begin
    g_bFlag:=True;
    with   NetSource   do
    begin
        dwType   :=   RESOURCETYPE_ANY;
        lpLocalName   :='';
        lpRemoteName:='\\192.18.11.21';
        lpProvider     :='';
    end;
    dwResult:=WnetAddConnection2(NetSource,'123456','lxx',CONNECT_UPDATE_PROFILE);
    if dwResult<>0 then
    begin
        ShowMessage('连接服务器失败!');
        g_bFlag:=False;
    end
    else
    begin
      if winexec('net use \\192.18.11.21\I$ 123456 /user:lxx',SW_HIDE)>31 then
          Sleep (3000)
      else
      begin
          application.MessageBox('登录失败.','提示信息',48);
          exit;
      end;

      //从服务里拷贝文件到本地D盘
      if copyfile(PChar('I:/wenjianjia/2.txt'),PChar('d:/1.txt'),false) then
        application.MessageBox('文件复制成功.','提示信息',64)
      else
        application.MessageBox('文件复制失败.','提示信息',48);

      //直接打开共享文件夹
      ShellExecute(0, 'open', pchar('I:/wenjianjia/'), '', '', SW_SHOW);
      ShowMessage('OK!');
    end;
end;


procedure TForm1.DisConnectServer;
begin
  if g_bFlag then
  WNetCancelConnection2('\\192.18.11.21',CONNECT_UPDATE_PROFILE,True);
end;


procedure TForm1.Button2Click(Sender: TObject);
begin
  DisConnectServer;
end;


end.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值