活动目录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(constName: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.Adddobegin

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)asIEnumVariant;

while(Enum.Next(1,ADsTempOjb,Value)=S_OK)dobegin

ADsObj:=IUnknown(ADsTempOjb)asIADs;

try

ifSameText(ADsObj.Class_,'Group')thenbegin

AddGroupToListView(ADsObjasIADsGroup);

EnumerateUsers(ADsObjasIAdsContainer);

end

elseifSameText(ADsObj.Class_,'User')then

AddUserToListView(ADsObjasIADsUser);

except

end;

end;

end;


functionTForm2.GetObject(constName: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')asIADsContainer;

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.