0

Can I programmatically and remotely create and delete Windows User accounts via WCF (self hosted) and C#? This works locally, but not via WCF... Ideas?

            DirectoryEntry localDirectory = new DirectoryEntry("WinNT://" + Environment.MachineName.ToString());
            DirectoryEntries users = localDirectory.Children;
            try
                {
                    DirectoryEntry user = users.Find(usernameAccount);
                    users.Remove(user);

                }catch(SystemException)
                {
                    System.Console.WriteLine("Error: User account not found in the system");
                }
            }
Matt Davis
  • 45,297
  • 16
  • 93
  • 124
Manolete
  • 3,431
  • 7
  • 54
  • 92
  • I think it is worth noting that DirectoryEntry is IDisposable and its probably a good idea to wrap it in a using. using(DirectoryEntry user = users.Find(usernameAccount)) { users.Remove(user); } – Felan Jun 21 '11 at 20:53

2 Answers2

3

It should work, as long as the credentials with which the service is running have the appropriate permission to delete the account. If the default credentials in which the service code runs do not have such permission, you may want to look into impersonating the client to do that.

carlosfigueira
  • 85,035
  • 14
  • 131
  • 171
  • Carlos, you were right. It worked. I just needed to update the code on the client...Thanks everybody anyway. – Manolete Jun 22 '11 at 11:11
0

I had the some problem connecting to the remote windows with the error Error (0x80004005): Unspecified error. I resolved as follows:

//Define path
//This path uses the full path of user authentication
String path = string.Format("WinNT://{0}/{1},user", server_address, username);
DirectoryEntry deBase = null;
try
{
    //Try to connect with secure connection
    deBase = new DirectoryEntry(_ldapBase, _username, _passwd, AuthenticationTypes.Secure);

    //Connection test
    //After test define the deBase with the parent of user (root container)
    object nativeObject = _deRoot.NativeObject;
    _deRoot = _deRoot.Parent;

}
catch (Exception ex)
{
    //If an error occurred try without Secure Connection
    try
    {
        _deRoot = new DirectoryEntry(_ldapBase, _username, _passwd);

        //Connection test
        //After test define the deBase with the parent of user (root container)
        object nativeObject = _deRoot.NativeObject;
        _deRoot = _deRoot.Parent;
        nativeObject = _deRoot.NativeObject;

    }
    catch (Exception ex2)
    {
        //If an error occurred throw the error
        throw ex2;
    }
}
Federico Piazza
  • 30,085
  • 15
  • 87
  • 123