Delphi访问活动目录

活动目录Active Directory是用于Windows Server的目录服务,它存储着网络上各种对象的有关信息,并使该信息易于管理员和用户查找及使用。Active Directory使用结构化的数据存储作为目录信息的逻辑层次结构的基础。

在某些情况下我们需要通过程序来读取Active Directory中的信息,我们可以使用微软提供的ADSI(Active Directory Services Interface)。ADSI是一组以COM接口形式提供的目录 服务,因此任何支持COM编程的语言如Delphi、VB、VC等都可以使用ADSI。

在Delphi中使用ADSI需要导入活动目录类型库,具体操作如下:在IDE中选择菜单“Project->Import Type Library”,在弹出的对话框中选择“Active Ds Type Libarary(version 1.0)”,单击“Create Unit”,Delphi会自动产生封装单元文件。只要在相应文件中引用该单元文件即可使用ADSI了。下面给出一个在Delphi6中使用ADSI访问Windows Server活动目录信息的示例代码。

unitUnit2;

interface

uses
Windows,Messages,SysUtils,Variants,Classes,Graphics,Controls,Forms,
Dialogs,ActiveDs_TLB,ActiveX,ComObj,ComCtrls,StdCtrls;

type
TForm2
= class (TForm)
GroupBox1:TGroupBox;
lvGroup:TListView;
GroupBox2:TGroupBox;
lvUser:TListView;
Button1:TButton;
procedureButton1Click(Sender:TObject);
private
... {Privatedeclarations}
functionGetObject(
const Name:String):IDispatch;
procedureEnumerateUsers(Container:IAdsContainer);
procedureAddGroupToListView(AGroup:IADsGroup);
procedureAddUserToListView(AUser:IAdsUser);
public
... {Publicdeclarations}
end;

var
Form2:TForm2;

implementation

... {$R*.dfm}

... {TForm2}

procedureTForm2.AddGroupToListView(AGroup:IADsGroup);
begin
lvGroup.Items.Add.Caption:
= AGroup.Name;
end;

procedureTForm2.AddUserToListView(AUser:IAdsUser);
begin
withlvUser.Items.Add
do begin
Caption:
= AUser.FullName;
SubItems.Add(VarToStr(AUser.Get(
' sAMAccountName ' )));
end;
end;

procedureTForm2.EnumerateUsers(Container:IAdsContainer);
var
ADsObj:IADs;
Value:LongWord;
Enum:IEnumVariant;
ADsTempOjb:OleVariant;
begin
Enum:
= (Container._NewEnum) as IEnumVariant;
while (Enum.Next( 1 ,ADsTempOjb,Value) = S_OK) do begin
ADsObj:
= IUnknown(ADsTempOjb) as IADs;
try
if SameText(ADsObj.Class_, ' Group ' )thenbegin
AddGroupToListView(ADsObj
as IADsGroup);
EnumerateUsers(ADsObj
as IAdsContainer);
end
else if SameText(ADsObj.Class_, ' User ' )then
AddUserToListView(ADsObj
as IADsUser);
except
end;
end;
end;

functionTForm2.GetObject(
const Name:String):IDispatch;
var
Eaten:Integer;
Moniker:IMoniker;
BindContext:IBindCtx;
begin
OleCheck(CreateBindCtx(
0 ,BindContext));
OleCheck(MkParseDisplayName(BindContext,PWideChar(WideString(Name)),Eaten,Moniker));
OleCheck(Moniker.BindToObject(BindContext,Nil,IDispatch,Result));
end;

procedureTForm2.Button1Click(Sender:TObject);
var
Container:IADsContainer;
begin
Container:
= GetObject( ' LDAP://OU=Suzhou,OU=root,DC=ap,DC=emersonclimate,DC=org ' ) as IADsContainer;
lvGroup.Items.BeginUpdate;
lvUser.Items.BeginUpdate;
try
Button1.Enabled:
= False;
EnumerateUsers(Container);
Button1.Enabled:
= True;
finally
lvGroup.Items.EndUpdate;
lvUser.Items.EndUpdate;
end;
Container._Release;
end;

end.

版权声明:本文为博主原创文章,未经博主允许不得转载。

你可能感兴趣的:(windows,Delphi)