DirectoryEntry 또는 객체 계층을 통한 루핑 -C#
-
22-08-2019 - |
문제
현재 System.DirectoryServices 네임 스페이스를 사용하는 응용 프로그램을 개발하고 있습니다.
계층 구조에서 각 DirectoryEntry 오브젝트에 대한 자식 항목 수를 모르므로 어린이 재산을 통해 거미에게 N 수의 중첩 루프를 만들 수 없습니다.
내 의사 코드 예는 다음과 같습니다.
//root directory
DirectoryEntry root = new DirectoryEntry(path);
if(DirectoryEntry.Childern != null)
{
foreach(DirectoryEntry child in root.Children)
{
//loop through each Children property unitl I reach the last sub directory
}
}
내 질문은 객체의 하위 디렉토리 수를 모르는 경우 정보를 수집하기 위해 루프를 작성하는 가장 좋은 방법은 무엇입니까?
(이것은 객체 계층을 모르는 모든 유형의 객체에 적용될 수 있습니다)
해결책
계층 구조의 깊이를 모르고 모든 수준을 통과 해야하는 경우 재귀 기능을 사용하십시오. 아래는 깊이 우선 트래버스를 사용하는 예입니다.
using (DirectoryEntry root = new DirectoryEntry(someDN))
{
DoSomething(root);
}
function DoSomething(DirectoryEntry de)
{
// Do some work here against the directory entry
if (de.Children != null)
{
foreach (DirectoryEntry child in de.Children)
{
using (child)
{
DoSomething(child);
}
}
}
}
또는 재귀 없이는 큐 또는 스택 데이터 구조를 추가하고 아직 방문했지만 방문한 객체를 저장하여 트래버스를 수행 할 수 있습니다.
Queue<DirectoryEntry> queue = new Queue<DirectoryEntry>();
DirectoryEntry root = new DirectoryEntry(someDN);
queue.Add(root);
while (queue.Any())
{
using (DirectoryEntry de = queue.Dequeue())
{
// Do some work here against the directory entry
if (de.Children != null)
{
foreach (DirectoryEntry child in de.Children)
{
queue.Enqueue(child);
}
}
}
}
다른 팁
재귀 기능을 작성해야합니다 ...
DirectoryEntry root = new DirectoryEntry(path);
DoForEveryNode(root);
void DoForEveryNode(DirectoryEntry node)
{
// do something..
foreach(DirectoryEntry child in node.Children)
{
DoForEveryNode(child);
}
}
아이들에게 재귀 적으로 부르는 함수를 사용할 수 있습니다. 종료 조건 : 더 이상 어린이 등 ..
한 가지 옵션은 재귀를 사용하는 것입니다. 해당 코드를 함수로 설정 한 다음 Foreach 루프 내부를 호출하고 매번 다음 디렉토리 (자식 항목)를 전달합니다.
멋진 재귀 세계에 오신 것을 환영합니다. 디렉토리를 인수로 받아들이는 함수가 필요합니다. 그 디렉토리를 감안할 때, 그것은 모든 아동 디렉토리를 찾아서 각각의 디렉토리를 찾습니다.
제휴하지 않습니다 StackOverflow