|
发表于 2020-8-8 08:00:01
|
显示全部楼层
//建立远程连接 xPath: 远程路径 xNetUser/xNetPassword: 可以指定用户名及密码
function AddNetConnection(xPath, xNetUser, xNetPassword: string): string;
var
mNetSource: TNetResource;
mNetUser, mNetPassword: PChar;
mErrorCode: Cardinal;
begin
Result := '';
if Copy(xPath, 1, 2) <> '\\' then Exit; //非远程方式,退出
try
with mNetSource do
begin
dwScope := RESOURCE_GLOBALNET;
dwType := RESOURCETYPE_ANY;
dwDisplayType := RESOURCEDISPLAYTYPE_SHARE;
dwUsage := RESOURCEUSAGE_CONNECTABLE;
lpLocalName := nil; //这里可以指定本地驱动器名,则将xPath映射为本地驱动器,传nil,只与xPath建立远程连接
lpRemoteName := LPTSTR(xPath);
lpComment := nil;
lpProvider := nil;
end;
if xNetUser <> '' then
begin
mNetUser := LPTSTR(xNetUser);
mNetPassword := LPTSTR(xNetPassword);
end
else
begin
mNetUser := nil;
mNetPassword := nil;
end;
mErrorCode := WNetAddConnection2(mNetSource, mNetPassword, mNetUser, CONNECT_UPDATE_PROFILE);
if mErrorCode <> NO_ERROR then //映射失败
Result := Format('与 %s 建立网络连接时发生错误! 错误信息: %s', [xPath, SysErrorMessage(mErrorCode)]);
except
on E: Exception do
Result := Format('与 %s 建立网络连接时发生错误! 错误信息: %s', [xPath, E.Message]);
end;
end;
//mPath如果传入远程路径,则断开与远程路径的网络连接
//mPath如果传入本地驱动器名,则断开本地驱动器
function CancelNetConnection(xPath: string): string;
var
mErrorCode: Cardinal;
begin
Result := '';
if Copy(xPath, 1, 2) <> '\\' then Exit; //非远程方式,退出
try
mErrorCode := WNetCancelConnection2(LPTSTR(xPath), CONNECT_UPDATE_PROFILE, True);
if mErrorCode = NO_ERROR then
Result := Format('与 %s 断开网络连接时发生错误! 错误信息: %s', [xPath, SysErrorMessage(mErrorCode)]);
except
on E: Exception do
Result := Format('与 %s 断开网络连接时发生错误! 错误信息: %s', [xPath, E.Message]);
end;
end; |
|