Disconnect Local Windows User Using C#

131 views Asked by At

I have created two test accounts test and test1. I am able to login to one local windows user account "test" using the following code.

bool result = false;

            ContextType contextType = ContextType.Machine;

            //if (InDomain())
            //{
            //    contextType = ContextType.Domain;
            //}

            try
            {
                using (PrincipalContext principalContext = new PrincipalContext(contextType))
                {
                    result = principalContext.ValidateCredentials(
                        userName,
                        new NetworkCredential(string.Empty, password).Password
                    );
                }
            }
            catch (PrincipalOperationException)
            {
                // Account disabled? Considering as Login failed
                result = false;
            }
            catch (Exception)
            {
                throw;
            }

            return result;

However when I try to login with another account "test1", it throws the following exception.

Multiple connections to a server or shared resource by the same user, using more than one user name, are not allowed. Disconnect all previous connections to the server or shared resource and try again

It seems to me that the previous user "test" is already connected and occupies the resources, that is why it is not letting the user "test1" to get logged in and acquire the resources.

I have tried to find a way so that the first user "test" can be disconnected (or logged off) so that the 2nd user can get logged in.

I had tried to access the UserPrinciple through following code to get the connected user to disconnect but there is no method available in UserPrinciple

UserPrincipal userPrincipal = UserPrincipal.FindByIdentity(principalContext, "test");

There must be some way to log off (or disconnect) the logged in user.

1

There are 1 answers

0
PMF On

I don't know whether there's a nicer solution, but you could try a workaround using the net use command. By hand:

  1. Run net use
  2. Identify the relevant connections
  3. Run net use /d <connection> for all relevant connections
  4. Connect using the new user