Get windows operating system for all users

First, a brief knowledge

1. Using WindowsApi get

[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);

It should be taken from the Computer Management -> System Tools -> Local Users and Groups -> Users

Second, the specific examples

1. The introduction of the above-described API interface

2. The method of packaging into a

[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;
}

 

 

Guess you like

Origin www.cnblogs.com/yokeqi/p/11890535.html