list all local users using directory services - c#

The following method I created seem does not work. An error always happens on foreach loop.
NotSupportedException was unhandled...The provider does not support
searching and cannot search WinNT://WIN7,computer.
I'm querying the local machine
private static void listUser(string computer)
{
using (DirectoryEntry d= new DirectoryEntry("WinNT://" +
Environment.MachineName + ",computer"))
{
DirectorySearcher ds = new DirectorySearcher(d);
ds.Filter = ("objectClass=user");
foreach (SearchResult s in ds.FindAll())
{
//display name of each user
}
}
}

You cannot use a DirectorySearcher with the WinNT provider. From the documentation:
Use a DirectorySearcher object to search and perform queries against an Active Directory Domain Services hierarchy using Lightweight Directory Access Protocol (LDAP). LDAP is the only system-supplied Active Directory Service Interfaces (ADSI) provider that supports directory searching.
Instead, use the DirectoryEntry.Children property to access all child objects of your Computer object, then use the SchemaClassName property to find the children that are User objects.
With LINQ:
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry computerEntry = new DirectoryEntry(path))
{
IEnumerable<string> userNames = computerEntry.Children
.Cast<DirectoryEntry>()
.Where(childEntry => childEntry.SchemaClassName == "User")
.Select(userEntry => userEntry.Name);
foreach (string name in userNames)
Console.WriteLine(name);
}
Without LINQ:
string path = string.Format("WinNT://{0},computer", Environment.MachineName);
using (DirectoryEntry computerEntry = new DirectoryEntry(path))
foreach (DirectoryEntry childEntry in computerEntry.Children)
if (childEntry.SchemaClassName == "User")
Console.WriteLine(childEntry.Name);

The following are a few different ways to get your local computer name:
string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);
The next one is a way to get the current user name:
string name = System.Windows.Forms.SystemInformation.UserName;

Related

get windows users with group name using C# [duplicate]

I have a ASP.NET Website project and I need to list all the users and their groups on my Windows system. I have set the identity impersonation to true and provided the username and password of the admin in the web.config. Where do I start?
Thanks in advance.
Update:
I have the following code at the moment -
var machine = new DirectoryEntry("WinNT://<IP ADDRESS>");
foreach (DirectoryEntry child in machine.Children)
{
// get the child's group(s).
}
When I debug, I can see the list of users in machine.Children. How do I find the group(s) that this user belongs to?
This article covers how to talk to Active Directory and should get you where you want to go:
http://www.codeproject.com/KB/system/everythingInAD.aspx
To get users, you would do something like this:
public List<string> GetUserList()
{
string DomainName="";
string ADUsername="";
string ADPassword="";
List<string> list=new List<string>();
DirectoryEntry entry=new DirectoryEntry(LDAPConnectionString, ADUsername, ADPassword);
DirectorySearcher dSearch=new DirectorySearcher(entry);
dSearch.Filter="(&(objectClass=user))";
foreach(SearchResult sResultSet in dSearch.FindAll())
{
string str=GetProperty(sResultSet, "userPrincipalName");
if(str!="")
list.Add(str);
}
return list;
}
You probably want to start with the DirectoryEntry and Active Directory support in .net.
Here's a good resource: http://www.codeproject.com/KB/system/everythingInAD.aspx
Local access is similar, even if you're not in a domain:
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" +
Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators",
"group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members) {
DirectoryEntry member = new DirectoryEntry(groupMember);
//...
}

Query Local Administrator Group

So, I'm kind of stuck here...
I'm writing a program that should be able to list all users in the local administrator group on a MS Windows Server 2008 R2.
The problem here is that I'm only allowed to use .NET 2.0 - so I'm not able to use the GroupPrincipal Class... Which would have made this a really easy task.
Any pointers would be appriciated!
Cheers!
Jeez!
Don't know what I was thinking really - it's so simple!
All creds to Masoud Tabatabaei - found the following codesnippet on:
http://csharptuning.blogspot.se/2007/09/how-to-get-list-of-windows-user-in-c.html
DirectoryEntry localMachine = new DirectoryEntry("WinNT://" + Environment.MachineName);
DirectoryEntry admGroup = localMachine.Children.Find("administrators","group");
object members = admGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
lstUsers.Items.Add(member.Name);
}
Did you try WMI ?
for example
ManagementObjectSearcher search = new ManagementObjectSearcher(#"SELECT * FROM Win32_UserAccount where LocalAccount = true");
ManagementObjectCollection userList = search.Get();
foreach (ManagementObject user in userList)
{
Console.WriteLine("User name: {0}, Full Name: {1}",
user["Name"].ToString(), user["FullName"].ToString());
}
Will give you a list of users in local SAM. You can add other attributes to the query and refine your list.
Do not forget to add a reference to System.Management.dll
If your are still looking for an answer, here:
If you'd like to get the administrator group, you can use this code:
public static DirectoryEntry GetLocalAdminstratorGroup()
{
using (var WindowsActiveDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName + ",computer"))
{
return WindowsActiveDirectory.Children.Find(GetLocalizedAdministratorGroupName(), "group");
}
}
//Localized == Language Independent
public static string GetLocalizedAdministratorGroupName()
{
//For English Windows version, this equals "BUILTIN\Administrators".
var adminGroupName = new SecurityIdentifier(WellKnownSidType.BuiltinAdministratorsSid, null).Translate(typeof(NTAccount)).Value;
//Remove the "BUILTIN\" part, get the local name of the group
return adminGroupName.Split('\\')[1];
}
If you'd also like to enumerate it (like you need a username), you can do this, using the methods before:
object members = AdminGroup.Invoke("members", null);
foreach (object groupMember in (IEnumerable)members)
{
DirectoryEntry member = new DirectoryEntry(groupMember);
Console.WriteLine(member.Name);
}

How to retrieve DirectoryEntry from a DirectoryEntry and a DN

I have a DirectoryEntry object representing a user. From the DirectoryEntry.Properties collection, I am retrieving the "manager" property, which will give me a Distinguished Name ("DN") value for the user's manager.
Can I retrieve a DirectoryEntry object for the manager from just these two objects? If so, how?
I'm envisioning something like DirectoryEntry.GetEntryFromDN(dnManager);, but I cannot find a similar call.
Just to clarify, the DirectoryEntry and DN are the only pieces of information I have. I cannot instantiate a new DirectoryEntry because then I would have have to either use the default Directory and credentials or have the Directory name/port and username/password.
DirectoryEntry User = YourPreExistingUser();
string managerDN = User.Properties["manager"][0].ToString();
// Browse up the object hierarchy using DirectoryEntry.Parent looking for the
// domain root (domainDNS) object starting from the existing user.
DirectoryEntry DomainRoot = User;
do
{
DomainRoot = DomainRoot.Parent;
}
while (DomainRoot.SchemaClassName != "domainDNS");
// Use the domain root object we found as the search root for a DirectorySearcher
// and search for the manager's distinguished name.
using (DirectorySearcher Search = new DirectorySearcher())
{
Search.SearchRoot = DomainRoot;
Search.Filter = "(&(distinguishedName=" + managerDN + "))";
SearchResult Result = Search.FindOne();
if (Result != null)
{
DirectoryEntry Manager = Result.GetDirectoryEntry();
}
}
You can create a new DirectoryEntry instance providing the the DN as argument and then
attempt to bind (by refreshing properties for example).
DirectoryEntry e = new DirectoryEntry(dn, "u", "p");
e.RefreshCache();

"The specified domain either does not exist or could not be contacted."

I'm trying to use the DomainServices class to retrieve a list of OU's from my Active Directory.
Here's my code:
public List<OrganizationalUnit> FindOrganizationalUnits(string domainName, string domainExtension, string parentOrganizationUnit)
{
string tmpDirectory = String.Format("LDAP://ou={0},dc={1},dc={2}",
parentOrganizationUnit,
domainName,
domainExtension
);
DirectoryEntry directory = new DirectoryEntry(tmpDirectory);
DirectorySearcher searcher = new DirectorySearcher(directory);
searcher.Filter = "(objectClass=organizationalUnit)";
searcher.SearchScope = SearchScope.Subtree;
searcher.PropertiesToLoad.Add("displayName");
var organizationalUnits = new List<OrganizationalUnit>();
foreach (SearchResult result in searcher.FindAll())
{
//I just create and return a new OrganizationalUnit object based on the SearchResult result.
organizationalUnits.Add(new OrganizationalUnit(result));
}
return organizationalUnits;
}
Is there some configuration I have to set on my server end to let me use DirectoryServices to query it's AD objects?
Thanks for the help.
What type of app are you running this code from? AD queries have to be made from an authenticated resource. You can either use the current credentials of the user, or pass in a new name/password.
Services usually don't have any issue, running under LocalSystem, but if this is a web app running under IIS standard permissions, it might cause an issue.
Try adding some credentials where you're instantiating your DirectoryEntry class.

Directory Services, Search all available providers

I have the following method used for searching for a User Group either on the local computer (done first) or in the Current Forest.
public string FindUserGroup(string group)
{
//Search local computer
using (DirectorySearcher searcher = new DirectorySearcher(new DirectoryEntry()))
{
searcher.Filter = "(&(objectClass=group)(|(cn=" + group + ")(dn=" + group + ")))";
SearchResult result = searcher.FindOne();
if (result != null)
return TranslateDirectoryEntryPath(result.GetDirectoryEntry().Path);
}
//Search current forest
Forest forest = Forest.GetCurrentForest();
foreach (Domain domain1 in forest.Domains)
{
using (DirectorySearcher searcher = new DirectorySearcher(domain1.GetDirectoryEntry()))
{
searcher.Filter = "(&(objectClass=group)(|(cn=" + group + ")(dn=" + group + ")))";
SearchResult result = searcher.FindOne();
if (result != null)
return TranslateDirectoryEntryPath(result.GetDirectoryEntry().Path);
}
}
return string.Empty;
}
My problem is that we as an example have say "domain.local" and "mydomain.local", and my current login is bound to "domain.local", then using below won't be able to find anything in "mydomain.local", even if I through the Windows User Interface is able to.
How can I search all viewable providers from my computers perspective when I don't nessesarily know them all? Do I REALLY have to do the Registry Work my self?
Edit:
One difference in the 2 domains is the "level" they are on when I in an object browser dialog chooses "Locations", it layouts as:
Computer
Entire Direction
domain.local
mydomain.local
So "mydomain.local" excists outside what is referred to as "Entire Directory", yet my computer can locate it, if that makes any difference?
I don't see a problem as this code here would have already be binded to the other domains.
foreach (Domain domain1 in forest.Domains)
{
using (DirectorySearcher searcher = new DirectorySearcher(domain1.GetDirectoryEntry()))
{
Are you trying to say that later on you're binding a DirectoryEntry on your own, and you can't find objects from other domain?

Categories