I'm working on an application which as an interface requiring the user's name to be provided as components (first, middle, last).
When setting up a user in AD the user dialog has text boxes for (first, middle, last) and then combines these into a display name.
I can retrieve these parts using System.DirectoryServices.AccountManagement by doing something like the following:
UserPrincipal userPrinciple = UserPrincipal.Current;
Name.GivenName = userPrinciple.GivenName;
Name.MiddleName = userPrinciple.MiddleName;
Name.FamilyName = userPrinciple.Surname;
Now unfortunately, UserPrincipal throws an exception if the system is disconnected from the domain. In that situation I fall back to GetUserNameEx.
[DllImport("secur32.dll", CharSet = CharSet.Auto)]
public static extern bool GetUserNameEx(int nameFormat, StringBuilder userName, ref uint userNameSize);
StringBuilder fullname = new StringBuilder(1024);
uint size = (uint)fullname.Capacity;
GetUserNameEx(3, fullname, ref size)
Here I am left to fend for myself and break the full name into its components. Does anyone know a way to get the components when the system is disconnected from the domain?
Similarly, if the system is not part of a domain and local accounts are being used I resort to WMI.
string UserName = Environment.UserName;
string query = "SELECT * FROM Win32_UserAccount Where Name=\"" + UserName + "\"";
ManagementScope mgmtScope = new ManagementScope("\\\\.\\Root\\CIMv2");
ObjectQuery oQuery = new ObjectQuery(query);
ManagementObjectSearcher mgmtSearch = new ManagementObjectSearcher(mgmtScope, oQuery);
ManagementObjectCollection objCollection = mgmtSearch.Get();
foreach (ManagementObject mgmtObject in objCollection)
{
fullName = (string)mgmtObject["FullName"];
}
I am again left to break the name up on my own. Does anyone know a way to get the components when the system is in a workgroup using local accounts?
When I looked at the local user management dialog it appears to have some differences from the AD user dialog. It appears to lack the text boxes for providing the (first, middle, last) names and only has a full name text box.