private static void AddUserToAdminGroup(string adminGroupName, byte[] userSid) { // Add the user's SID to local admins group. IntPtr userSidNative = Marshal.AllocHGlobal(userSid.Length); Marshal.Copy(userSid, 0, userSidNative, (int)userSid.Length); NativeMethods.LOCALGROUP_MEMBERS_INFO_0 info0; info0.PSID = userSidNative; NativeMethods.NetUserRetEnum netUserRet = NativeMethods.NetLocalGroupAddMembers( null, adminGroupName, 0, ref info0, 1); Marshal.FreeHGlobal(userSidNative); if (NativeMethods.NetUserRetEnum.NerrSuccess != netUserRet) { FailWithError("NetLocalGroupAddMembers", netUserRet: netUserRet); } }
private static void FailWithError( string method, NativeMethods.NetUserRetEnum netUserRet = NativeMethods.NetUserRetEnum.NerrSuccess) { int error; string message; if (NativeMethods.NetUserRetEnum.NerrSuccess != netUserRet) { error = (int)netUserRet; message = netUserRet.ToString(); } else { error = Marshal.GetLastWin32Error(); message = new Win32Exception(error).Message; } Logger.Warning("{0} failed with error {1}: {2}", method, error, message); throw new Win32Exception(error, message); }