Part 6 Check for Existing Account

Create the class that will check if the user exists in Active Directory.

Once again, this example uses the AresAdmin account used in the ChangePassword.cs class.

Copy the method used to create the Globals.cs class but this time call it ‘CheckIfExists.cs’.

Change the code inside CheckIfExists.cs to the following:

using System;
using System.DirectoryServices.AccountManagement;
using System.Security;
using System.Runtime.InteropServices;

namespace Acre
{
class CheckIfExists
{
public string ADExists(string accountVariable)
{
string accountExists = “Maybe”;

try
{
#region payload

//Check if the account exists

PrincipalContext context = new PrincipalContext(ContextType.Domain, “mydomain.local”, “AresAdmin”, “123456789012345”);

UserPrincipal user = UserPrincipal.FindByIdentity(context, System.DirectoryServices.AccountManagement.IdentityType.SamAccountName, accountVariable);

if (user != null)
{
accountExists = “Yes”;
}
else
{
accountExists = “No”;
}
#endregion
}
catch (Exception e)
{
Globals.errorCode = e.ToString();
}

return accountExists;
}

private static string GetStringFromSecureString(SecureString secStr)
{
if (secStr == null)
{
return null;
}

IntPtr pPlainText = IntPtr.Zero;

try
{
pPlainText = Marshal.SecureStringToBSTR(secStr);
return Marshal.PtrToStringBSTR(pPlainText);
}
finally
{
if (pPlainText != IntPtr.Zero)
{
Marshal.FreeBSTR(pPlainText);
}
}
}
}
}

About the author: Author

Leave a Reply