/// <summary> /// Resolves the domain and username of a user as specified by a SID. /// </summary> /// <param name="sid"> The SID to resolve. </param> /// <param name="domain"> The domain the resolved user belongs to. </param> /// <param name="user"> The username of the resolved user. </param> /// <returns> /// true if the SID was successfully resolved, false otherwise. /// </returns> /// <remarks> /// <value> /// For well-known-users/SIDs, the resolved username depends on the system language. /// </value> /// </remarks> /// <exception cref="ArgumentNullException"> <paramref name="sid" /> is null. </exception> /// <exception cref="Win32Exception"> The resolve failed. </exception> public static bool GetUserFromSid(SecurityIdentifier sid, out string domain, out string user) { if (sid == null) { throw new ArgumentNullException(nameof(sid)); } domain = null; user = null; byte[] sidBytes = new byte[sid.BinaryLength]; sid.GetBinaryForm(sidBytes, 0); uint capacity = 1024; StringBuilder domainBuilder = new StringBuilder((int)capacity); StringBuilder nameBuilder = new StringBuilder((int)capacity); bool success = WindowsUser.LookupAccountSid(null, sidBytes, nameBuilder, ref capacity, domainBuilder, ref capacity, out _); if (!success) { int errorCode = WindowsApi.GetLastErrorCode(); if (errorCode != (int)WindowsError.ErrorNoneMapped) { string errorMessage = WindowsApi.GetErrorMessage(errorCode); throw new Win32Exception(errorCode, errorMessage); } return(false); } domain = domainBuilder.ToString(); user = nameBuilder.ToString(); return(true); }