यदि आप .NET 3.5 या उससे ऊपर के हैं, तो आप नए System.DirectoryServices.AccountManagement
(S.DS.AM) नेमस्पेस का उपयोग कर सकते हैं जो इसे उपयोग करने की तुलना में बहुत आसान बनाता है।
इसके बारे में यहाँ पढ़ें: .NET ढाँचा 3.5 में निर्देशिका सुरक्षा प्रधानाचार्य
अपडेट: पुराने MSDN पत्रिका लेख अब ऑनलाइन नहीं हैं, दुर्भाग्य से - आपको जनवरी 2008 में Microsoft से MSDN पत्रिका के लिए CHM डाउनलोड करना होगा और उसमें लेख पढ़ना होगा।
मूल रूप से, आपको एक "प्रमुख संदर्भ" (आमतौर पर आपका डोमेन), एक उपयोगकर्ता प्रिंसिपल होना चाहिए, और फिर आपको इसके समूह बहुत आसानी से मिलेंगे:
public List<GroupPrincipal> GetGroups(string userName)
{
List<GroupPrincipal> result = new List<GroupPrincipal>();
// establish domain context
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find your user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, userName);
// if found - grab its groups
if(user != null)
{
PrincipalSearchResult<Principal> groups = user.GetAuthorizationGroups();
// iterate over all groups
foreach(Principal p in groups)
{
// make sure to add only group principals
if(p is GroupPrincipal)
{
result.Add((GroupPrincipal)p);
}
}
}
return result;
}
और बस इतना ही है! अब आपके पास प्राधिकरण समूहों का एक परिणाम (एक सूची) है जो उपयोगकर्ता के पास है - उन पर पुनरावृति, उनके नाम या जो कुछ भी आपको करने की आवश्यकता है उसका प्रिंट आउट लें।
अपडेट: कुछ गुणों को एक्सेस करने के लिए, जो UserPrincipal
ऑब्जेक्ट पर सामने नहीं आते हैं , आपको अंतर्निहित में खुदाई करने की आवश्यकता है DirectoryEntry
:
public string GetDepartment(Principal principal)
{
string result = string.Empty;
DirectoryEntry de = (principal.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
return result;
}
अपडेट # 2: लगता है कि कोड के इन दो स्निपेट को एक साथ रखना बहुत मुश्किल नहीं होना चाहिए .... लेकिन ठीक है - यहाँ यह जाता है:
public string GetDepartment(string username)
{
string result = string.Empty;
// if you do repeated domain access, you might want to do this *once* outside this method,
// and pass it in as a second parameter!
PrincipalContext yourDomain = new PrincipalContext(ContextType.Domain);
// find the user
UserPrincipal user = UserPrincipal.FindByIdentity(yourDomain, username);
// if user is found
if(user != null)
{
// get DirectoryEntry underlying it
DirectoryEntry de = (user.GetUnderlyingObject() as DirectoryEntry);
if (de != null)
{
if (de.Properties.Contains("department"))
{
result = de.Properties["department"][0].ToString();
}
}
}
return result;
}
UserPrincipal
- उस पर कैसे प्राप्त करें, इसके लिए मेरा अद्यतन उत्तर देखें।