活動目錄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活動目錄信息的示例代碼。
unit Unit2;
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;
procedure Button1Click(Sender: TObject);
private
...{ Private declarations }
function GetObject(const Name: String): IDispatch;
procedure EnumerateUsers(Container: IAdsContainer);
procedure AddGroupToListVIEw(AGroup: IADsGroup);
procedure AddUserToListVIEw(AUser: IAdsUser);
public
...{ Public declarations }
end;
var
Form2: TForm2;
implementation
...{$R *.dfm}
...{ TForm2 }
procedure TForm2.AddGroupToListVIEw(AGroup: IADsGroup);
begin
lvGroup.Items.Add.Caption := AGroup.Name;
end;
procedure TForm2.AddUserToListVIEw(AUser: IAdsUser);
begin
with lvUser.Items.Add do begin
Caption := AUser.FullName;
SubItems.Add(VarToStr(AUser.Get('sAMaccountName')));
end;
end;
procedure TForm2.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') then begin
AddGroupToListVIEw(ADsObj as IADsGroup);
EnumerateUsers(ADsObj as IAdsContainer);
end
else if SameText(ADsObj.Class_, 'User') then
AddUserToListVIEw(ADsObj as IADsUser);
except
end;
end;
end;
function TForm2.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;
procedure TForm2.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.