如何在Delphi中获取Windows本地用户的完整姓名
在Delphi中获取本地用户的完整姓名及其他详细信息
要获取本地用户的完整姓名、注册邮箱等GetUsernameEx无法提供的信息,你可以使用Windows原生的NetUserGetInfo API函数——它属于NetAPI32库,专门用于查询本地或域用户的详细属性。
核心思路
NetUserGetInfo支持不同的信息级别(Level),其中Level 2的结构包含我们需要的完整姓名、邮箱地址等字段。针对本地用户,只需将服务器参数设为nil或空字符串即可。
Delphi实现代码
首先需要定义API所需的结构和函数声明(若Delphi的Windows单元未完整包含相关定义):
{$APPTYPE CONSOLE} uses Windows, SysUtils; // 定义USER_INFO_2结构,包含完整姓名、邮箱等核心信息 type USER_INFO_2 = record usri2_name: LPWSTR; usri2_password: LPWSTR; usri2_password_age: DWORD; usri2_priv: DWORD; usri2_home_dir: LPWSTR; usri2_comment: LPWSTR; usri2_flags: DWORD; usri2_script_path: LPWSTR; usri2_auth_flags: DWORD; usri2_full_name: LPWSTR; usri2_usr_comment: LPWSTR; usri2_parms: LPWSTR; usri2_workstations: LPWSTR; usri2_last_logon: DWORD; usri2_last_logoff: DWORD; usri2_acct_expires: DWORD; usri2_max_storage: DWORD; usri2_units_per_week: DWORD; usri2_logon_hours: PBYTE; usri2_bad_pw_count: DWORD; usri2_num_logons: DWORD; usri2_logon_server: LPWSTR; usri2_country_code: DWORD; usri2_code_page: DWORD; usri2_user_sid: PSID; usri2_primary_group_id: DWORD; usri2_profile: LPWSTR; usri2_home_dir_drive: LPWSTR; usri2_password_expired: DWORD; end; PUSER_INFO_2 = ^USER_INFO_2; // 声明NetUserGetInfo和内存释放函数 function NetUserGetInfo(servername: LPCWSTR; username: LPCWSTR; level: DWORD; var bufptr: Pointer): DWORD; stdcall; external 'netapi32.dll' name 'NetUserGetInfo'; function NetApiBufferFree(buffer: Pointer): DWORD; stdcall; external 'netapi32.dll' name 'NetApiBufferFree';
示例函数:获取本地用户的完整姓名
function GetLocalUserFullName(const AUsername: string): string; var pUserInfo: PUSER_INFO_2; dwResult: DWORD; begin Result := ''; // 查询本地用户的Level 2信息 dwResult := NetUserGetInfo(nil, PWideChar(AUsername), 2, Pointer(pUserInfo)); try if dwResult = NERR_Success then begin if Assigned(pUserInfo^.usri2_full_name) then Result := WideString(pUserInfo^.usri2_full_name); end else RaiseLastOSError(dwResult); finally // 释放API分配的内存 if Assigned(pUserInfo) then NetApiBufferFree(pUserInfo); end; end;
扩展:获取用户注册邮箱
基于同样的逻辑,只需访问pUserInfo^.usri2_email字段即可获取邮箱信息:
function GetLocalUserEmail(const AUsername: string): string; var pUserInfo: PUSER_INFO_2; dwResult: DWORD; begin Result := ''; dwResult := NetUserGetInfo(nil, PWideChar(AUsername), 2, Pointer(pUserInfo)); try if dwResult = NERR_Success then begin if Assigned(pUserInfo^.usri2_email) then Result := WideString(pUserInfo^.usri2_email); end else RaiseLastOSError(dwResult); finally if Assigned(pUserInfo) then NetApiBufferFree(pUserInfo); end; end;
测试调用示例
var FullName, Email: string; begin try FullName := GetLocalUserFullName('rabi'); Writeln('用户完整姓名: ', FullName); Email := GetLocalUserEmail('rabi'); Writeln('用户注册邮箱: ', Email); except on E: Exception do Writeln('错误: ', E.Message); end; Readln; end.
注意事项
- 权限要求:普通用户权限通常可以查询本地用户的基本信息(如完整姓名、邮箱),部分敏感信息可能需要管理员权限。
- 错误处理:需妥善处理
NetUserGetInfo返回的错误码,例如NERR_UserNotFound表示指定的本地用户不存在。
内容的提问来源于stack exchange,提问作者mrabat
相关产品推荐
相关产品推荐

