DirectoryAccess クラスに追加したコンピュータ関連のメソッドのコードです。
VB(前回追加したコードはこちら)
'コンピュータを取得します。
Public Shared Function GetComputers() As IList(Of Computer)
Dim computers As New List(Of Computer)()
Using root = GetRootEntry() 'ルートのDirectoryEntryを取得
If CanConnectDomain Then 'ドメインに接続できる時
Dim filter = String.Format("(objectCategory={0})", CategoryType.Computer)
Using searcher As New DirectorySearcher(root, filter)
Using results = searcher.FindAll()
For Each res As SearchResult In results
computers.Add(DirectCast(CreateInstance(res.GetDirectoryEntry()), Computer))
Next
End Using
End Using
End If
End Using
Return computers
End Function
C#(前回追加したコードはこちら)
//コンピュータを取得します。
public static IList<Computer> GetComputers()
{
var computers = new List<Computer>();
using (var root = GetRootEntry()) //ルートのDirectoryEntryを取得
{
if (CanConnectDomain) //ドメインに接続できる時
{
var filter = String.Format("(objectCategory={0})", CategoryType.Computer);
GroupTokens.Clear();
using (var searcher = new DirectorySearcher(root, filter))
{
using (var results = searcher.FindAll())
{
foreach (SearchResult res in results)
{
computers.Add((Computer)CreateInstance(res.GetDirectoryEntry()));
}
}
}
}
}
return computers;
}
DirectoryObject のインスタンスを作成する CreateInstance メソッドにコンピュータ部分のコード(太字の部分)を追加しました。
VB
Private Shared Function CreateInstance(entry As DirectoryEntry) As DirectoryObject
Dim category As CategoryType
If [Enum].TryParse(Of CategoryType)(entry.SchemaClassName, True, category) = False Then
Throw New ArgumentException("entry の種類が CategoryType に該当しません。", "entry")
End If
Select Case category
Case CategoryType.User
If CanConnectDomain Then 'ドメインに接続できる時
Return New DomainUser(entry)
Else 'ドメインに接続できない時
Return New LocalUser(entry)
End If
Case CategoryType.Group
If CanConnectDomain Then 'ドメインに接続できる時
Return New DomainGroup(entry)
Else 'ドメインに接続できない時
Return New LocalGroup(entry)
End If
Case CategoryType.Computer
Return New Computer(entry)
Case Else
Throw New NotImplementedException()
End Select
End Function
C#
private static DirectoryObject CreateInstance(DirectoryEntry entry)
{
CategoryType category;
if (Enum.TryParse<CategoryType>(entry.SchemaClassName, true, out category) == false)
{
throw new ArgumentException("entry の種類が CategoryType に該当しません。", "entry");
}
switch (category)
{
case CategoryType.User:
if (CanConnectDomain) //ドメインに接続できる時
{
return new DomainUser(entry);
}
else //ドメインに接続できない時
{
return new LocalUser(entry);
}
case CategoryType.Group:
if (CanConnectDomain) //ドメインに接続できる時
{
return new DomainGroup(entry);
}
else //ドメインに接続できない時
{
return new LocalGroup(entry);
}
case CategoryType.Computer:
return new Computer(entry);
default:
throw new NotImplementedException();
}
}