获取Windows用户所有的账户名

 /// <summary>
        /// 设置用户密码
        /// </summary>
       [DllImport("Netapi32.dll")]
        extern static int NetUserEnum([MarshalAs(UnmanagedType.LPWStr)] string sName,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);
        /*
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct LOCALGROUP_USERS_INFO_0
        {
            public string GroupName;
        }
         */
        [StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
        public struct USER_INFO_1
        {
            public string sName;    //用户名
            public string sPass;    //用户密码
            public int PasswordAge; //密码级别
            public int sPriv;       //帐户类型 1
            public string sHomeDir; //用户主目录 null
            public string sComment; //用户描述
            public int sFlags;      //用户权限
            public string sScriptPath;  //登陆脚本路径 null
        }
        public List<string> UserEnum()
        {
            List<String> listNames = new List<string>();
            int Entriesread;
            int TotalEntries;
            int Resume_Handle;
            IntPtr bufPtr;
            if (NetUserEnum(null, 1, 0, out bufPtr, -1, out Entriesread, out TotalEntries, out Resume_Handle) != 0)
            {
                throw (new Exception("枚举全部用户失败"));
            }
            if (Entriesread > 0)
            {
                USER_INFO_1[] UserInfo = new USER_INFO_1[Entriesread];
                IntPtr iter = bufPtr;
                for (int i = 0; i < Entriesread; i++)
                {
                    UserInfo[i] = (USER_INFO_1)Marshal.PtrToStructure(iter,  typeof(USER_INFO_1));
                    iter = (IntPtr)((int)iter + Marshal.SizeOf(typeof(USER_INFO_1)));
                    listNames.Add(UserInfo[i].sName);
                    
                }
            }
            NetApiBufferFree(bufPtr);
            return listNames;
        }

Published by

风君子

独自遨游何稽首 揭天掀地慰生平

发表回复

您的电子邮箱地址不会被公开。 必填项已用 * 标注