At first I thought the code below works because if I have the group as \"IT\" it functions correctly because my username is in the IT group in active directory. What I learn
You cannot do it by this way. You should query the active directory. You can use a wrapper for AD. Check out http://www.codeproject.com/Articles/10301/Wrapper-API-for-using-Microsoft-Active-Directory-S
Slight deviation from @marc_s example, implemented in the static void Main()
method in Program
:
DomainCtx = new PrincipalContext( ContextType.Domain , Environment.UserDomainName );
if ( DomainCtx != null ) {
User = UserPrincipal.FindByIdentity( DomainCtx , Environment.UserName );
}
DomainCtx
and User
are both static properties declared under Program
Then in other forms i simply do something like this:
if ( Program.User.IsMemberOf(GroupPrincipal.FindByIdentity(Program.DomainCtx, "IT-All") )) {
//Enable certain Form Buttons and objects for IT Users
}
Since you're on .NET 3.5 and up, you should check out the System.DirectoryServices.AccountManagement
(S.DS.AM) namespace. Read all about it here:
Basically, you can define a domain context and easily find users and/or groups in AD:
// set up domain context
PrincipalContext ctx = new PrincipalContext(ContextType.Domain, "DOMAINNAME");
// find a user
UserPrincipal user = UserPrincipal.FindByIdentity(ctx, "SomeUserName");
// find the group in question
GroupPrincipal group = GroupPrincipal.FindByIdentity(ctx, "YourGroupNameHere");
if(user != null)
{
// check if user is member of that group
if (user.IsMemberOf(group))
{
// do something.....
}
}
The new S.DS.AM makes it really easy to play around with users and groups in AD!