获取Windows UserPrincipal DisplayName并调整显示顺序
Got it, let's work through this. The "LastName, FirstName (Department)" format you're seeing is typical for Active Directory user display names, and there are two reliable ways to get the "FirstName LastName" format you need.
Option 1: Parse the Existing DisplayName String
If you want to stick with using the DisplayName property directly, you can split and clean up the string to extract the first and last names. This works if the display name format is consistent across your users.
Here's the code:
public static string GetFormattedFullName() { string rawDisplayName = UserPrincipal.Current.DisplayName; if (string.IsNullOrWhiteSpace(rawDisplayName)) return string.Empty; // Split on the comma to separate last name from the rest of the string var nameSegments = rawDisplayName.Split(new[] { ',' }, 2); if (nameSegments.Length < 2) return rawDisplayName; // Fallback if the format doesn't match our expectation string lastName = nameSegments[0].Trim(); string firstPart = nameSegments[1].Trim(); // Remove the department suffix in parentheses int parenthesisStart = firstPart.IndexOf('('); if (parenthesisStart > 0) { firstPart = firstPart.Substring(0, parenthesisStart).Trim(); } return $"{firstPart} {lastName}"; }
Note: Add fallback logic (like returning the original display name) for cases where the format might differ—for example, users without a department listed, or display names that don't follow the comma-separated pattern.
Option 2: Fetch GivenName and Surname Directly from AD
A more robust approach is to pull the first and last names directly from their dedicated AD attributes (GivenName and Surname), instead of relying on the formatted DisplayName. This avoids issues if the display name ever gets modified or follows a different format.
Here's how to do it:
public static string GetFormattedFullName() { using (UserPrincipal currentUser = UserPrincipal.Current) { string firstName = currentUser.GivenName?.Trim() ?? string.Empty; string lastName = currentUser.Surname?.Trim() ?? string.Empty; // Combine and trim to avoid extra spaces if one of the fields is empty return $"{firstName} {lastName}".Trim(); } }
Why this is better: GivenName and Surname are core AD attributes, so they're less likely to change unexpectedly. Just make sure to handle null values (in case a user's first or last name isn't set in AD) to prevent null reference exceptions.
Quick Recommendation
If your environment has consistent display name formatting, either option works. But Option 2 is more reliable long-term because it doesn't depend on the display name's structure.
内容的提问来源于stack exchange,提问作者SomethingStrange

