Detect if a local user/group account exists

  • Thread starter Thread starter Roshan
  • Start date Start date
R

Roshan

Hi,

Given a name, I want to be able to detect if a user or a group account
exists with that name on a system and know if its a user or a group. My
search yielded the "LookupAccountName" Win32 API but I haven't found
any class in .NET that allows me to do that.

Does any one know of a class in .NET or a way of doing this without
using Win32 APIs ?

Thanks,
Roshan Achar
 
Hello,

I think, a quick hack would be this:

public bool GroupExists(string name) {
try
{
NTAccount account = new NTAccount(name);
acc.Translate(typeof(SecurityIdentifier));
return true;
}
catch (PrincipalNotMappedException)
{
return false;
}
}

Not very elegant, though.

Best regards,
Henning Krause
 
Thanks Henning.

This will suffice for the moment. It would have been better if an API
existed to do this directly.Also the Exception thrown is
IdentityNotMappedException
I found that I can detect if the name is a user or a group using

SecurityIdentifier.IsAccountSid(). It returns true if the name is a
local user account and false if its a group.

Thanks,
Roshan
 
Hi Henning,

I've been looking for this for a long time. But it solves just one problem
for me.
I want to test if a group exists, and if not, I want to create it.

How can i do this?

Any idea?
 
Hi Knut,

You can create a group as follows

using (DirectoryEntry AD = new DirectoryEntry("WinNT://" +
Environment.MachineName + ",computer"))
{
try
{
String typeName = "group";
String accountName = "KnutGroup";


using (DirectoryEntry NewUser =
AD.Children.Add(accountName, typeName))
{
NewUser.CommitChanges();
}
}
catch
{
Console.WriteLine("Error occured");
}
}

Hope this suffices,

Thanks,
Roshan
 
Hi Roshan,

that's great!!! Thank you!
I've been looking for the solution very long.

Best Regards
Knut
 
Back
Top