/// <summary> /// Resolves a user. /// </summary> /// <param name="user"> The user to resolve. </param> /// <returns> /// Either the user name specified by <paramref name="user" /> or the current user (<see cref="GetCurrentUser" />) if /// <paramref name="user" /> is an empty string or a ".". /// </returns> /// <exception cref="ArgumentNullException"> <paramref name="user" /> is null. </exception> public static string ResolveUser(string user) { if (user == null) { throw new ArgumentNullException(nameof(user)); } if (string.IsNullOrWhiteSpace(user) || string.Equals(user.Trim(), ".", StringComparison.InvariantCultureIgnoreCase)) { return(WindowsUser.GetCurrentUser()); } return(user); }
/// <summary> /// Extracts domain and user name from logon information. /// </summary> /// <param name="logon"> The logon information (either user or domain\user). </param> /// <param name="resolveDomain"> Specifies whether the extracted domain should be resolved. </param> /// <param name="resolveUser"> Specifies whether the extracted user should be resolved. </param> /// <param name="domain"> The extracted domain. Null if no domain information is available. </param> /// <param name="user"> The extracted user name. Null if no user information is available. </param> /// <exception cref="ArgumentNullException"> <paramref name="logon" /> is null. </exception> /// <exception cref="ArgumentException"> <paramref name="logon" /> is an empty string. </exception> public static void ExtractDomainAndUser(string logon, bool resolveDomain, bool resolveUser, out string domain, out string user) { if (logon == null) { throw new ArgumentNullException(nameof(logon)); } if (string.IsNullOrWhiteSpace(logon)) { throw new ArgumentException("The string is empty.", nameof(logon)); } int index = logon.IndexOf('\\'); if (index == -1) { domain = null; user = logon; } else { if (index == 0) { domain = null; } else { domain = logon.Substring(0, index); } if (index >= (logon.Length - 1)) { user = null; } else { user = logon.Substring(index + 1); } } user ??= string.Empty; domain ??= string.Empty; if (resolveUser) { if (string.IsNullOrWhiteSpace(user) || string.Equals(user.Trim(), ".", StringComparison.InvariantCultureIgnoreCase)) { user = WindowsUser.GetCurrentUser(); } } if (resolveDomain) { if (string.IsNullOrWhiteSpace(domain) || string.Equals(domain.Trim(), ".", StringComparison.InvariantCultureIgnoreCase)) { domain = WindowsUser.GetLocalDomain(); } } }