Reputation: 11
I have been researching for a solution for some time now:
I have tried System.DirectoryServices.AccountManagement
and System.DirectoryServices
.
Currently, I have gotten closes with System.Directory
services. Here is my code:
// Connect to pc
DirectoryEntry locaDirectoryEntry = new DirectoryEntry("WinNT://" + machineId);
// Find user by userName
DirectoryEntry user = locaDirectoryEntry.Children.Find(userName);
// Remove the user
locaDirectoryEntry.Children.Remove(user);
// Commit the changes
locaDirectoryEntry.CommitChanges();
This code deletes the user, so I cannot see it within "Local Users and Groups -> Users" but the user profile however stays and turns into "Account Unknown".
Now, I have been on numerous websites including this but have not been able to find something that does the trick "completely". I need the user profile to be deleted.
Any help/ thoughts is appreciated.
Upvotes: 0
Views: 1111
Reputation: 11
The code I specified above deletes a login from the computer but does not take care of the user profiles as stated by Damien_The_Unbeliever
.
I have been digging in my PowerShell equivalent to the app that I am making and found how I did it there. I use WMI to delete the user profile.
Here is my working code for any soul who could use it:
public string RemoveUser(string machineId, string userName)
{
string result = null;
try
{
// Create scope and set to computer root.
ManagementScope scope = new ManagementScope(@"\\" + machineId + @"\root\cimv2");
// Connect.
scope.Connect();
// Create the query for user profiles and a searcher.
SelectQuery query = new SelectQuery("Win32_UserProfile");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(scope, query);
// Go through each WMI Instance
foreach (ManagementObject mo in searcher.Get())
{
// Normalize username
string normalUser = mo["LocalPath"].ToString().Split('\\').Last();
// Check whether this is the user to be deleted
if (normalUser == userName)
{
mo.Delete();
result = "Found user: " + userName + ". Deleting...";
}
}
// This code deletes a user login
//DirectoryEntry locaDirectoryEntry = new DirectoryEntry("WinNT://" + machineId);
//DirectoryEntry user = locaDirectoryEntry.Children.Find(userName);
//locaDirectoryEntry.Children.Remove(user);
//locaDirectoryEntry.CommitChanges();
}
catch (Exception e)
{
throw new Exception(e.Message);
}
return result;
}
See the link for properties on UserProfiles
. Here is the Delete method.
Upvotes: 1