Thursday, August 21, 2008

Retrieve full name from Active Directory using C#

Once upon a time, I was given a task to build a simple attendance system to replace the attendance register in our office. Starting from sourceforge.net, I tried to find open source application to fit our requirement. After spending few hours in the Internet, I could not convinced myself with the applications that I came across. Then I suddenly realized that we are using Active Directory to log in to domain and also thought that if I could get the user detail from AD somehow, I can build a system which does not require any user login. Finally, I was able to find the code to get the full name of the current Windows user and build a small prototype for attendance system. The logic behind this application is to get the user detail from Active Directory and simply log attendance detail to another database. This will reduce the overhead of loggin in to the system as well as user administration part. Below is the code to get the full name of Windows user;
using System.DirectoryServices;

public static string GetFullName(string strLogin)
    {
        string str = "";
        string strDomain;
        string strName;

        // Parse the string to check if domain name is present.
        int idx = strLogin.IndexOf('\\');
        if (idx == -1)
        {
            idx = strLogin.IndexOf('@');
        }

        if (idx != -1)
        {
            strDomain = strLogin.Substring(0, idx);
            strName = strLogin.Substring(idx + 1);
        }
        else
        {
            strDomain = Environment.MachineName;
            strName = strLogin;
        }

        DirectoryEntry obDirEntry = null;
        try
        {
            obDirEntry = new DirectoryEntry("WinNT://" + strDomain + "/" + strName);
            System.DirectoryServices.PropertyCollection coll = obDirEntry.Properties;
            object obVal = coll["FullName"].Value;
            str = obVal.ToString();
        }
        catch (Exception ex)
        {
            str = ex.Message;
        }
        return str;
    }