获取windows操作系统所有用户

一、知识点简单介绍

1. 利用WindowsApi获取

[DllImport("Netapi32.dll ")]extern static int NetUserEnum([MarshalAs(UnmanagedType.LPWStr)] string servername, int level, int filter, out IntPtr bufptr, int prefmaxlen, out int entriesread, out int totalentries, out int resume_handle);[DllImport("Netapi32.dll ")]extern static int NetApiBufferFree(IntPtr Buffer);

应该是取自计算机管理 -> 系统工具 -> 本地用户和组 -> 用户

二、具体实例

1. 引入上述API接口

2. 封装成一个方法

[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]public struct USER_INFO_0{ public string Username;}public static List<string> GetSysUserNames(){ List<string> users = new List<string>(); NetUserEnum(null, 0, 2, out IntPtr bufPtr, -1, out int entriesRead, out int totalEntries, out int resume); if (entriesRead > 0) { IntPtr iter = bufPtr; for (int i = 0; i < entriesRead; i++) { var user = (USER_INFO_0)Marshal.PtrToStructure(iter, typeof(USER_INFO_0)); iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(USER_INFO_0))); users.Add(user.Username); } NetApiBufferFree(bufPtr); } return users;}

 

 

相关文章