可以通过以下步骤实现:
以下是一个示例代码,演示如何获取Windows中的本地计算机用户名列表:
using System;
using System.Runtime.InteropServices;
public class LocalUserManager
{
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode)]
private static extern int NetUserEnum(
string serverName,
int level,
int filter,
out IntPtr userInfo,
int prefMaxLen,
out int entriesRead,
out int totalEntries,
out int resumeHandle);
[DllImport("Netapi32.dll")]
private static extern int NetApiBufferFree(IntPtr buffer);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_0
{
public string UserName;
}
public static string[] GetLocalUserNames()
{
const int NERR_Success = 0;
const int MAX_PREFERRED_LENGTH = -1;
const int FILTER_NORMAL_ACCOUNT = 0x0002;
IntPtr userInfoPtr;
int entriesRead, totalEntries, resumeHandle;
int result = NetUserEnum(null, 0, FILTER_NORMAL_ACCOUNT, out userInfoPtr, MAX_PREFERRED_LENGTH,
out entriesRead, out totalEntries, out resumeHandle);
if (result != NERR_Success)
{
throw new Exception("Failed to retrieve local user names.");
}
string[] userNames = new string[entriesRead];
IntPtr iter = userInfoPtr;
for (int i = 0; i < entriesRead; i++)
{
USER_INFO_0 userInfo = (USER_INFO_0)Marshal.PtrToStructure(iter, typeof(USER_INFO_0));
userNames[i] = userInfo.UserName;
iter = (IntPtr)(iter.ToInt64() + Marshal.SizeOf(typeof(USER_INFO_0)));
}
NetApiBufferFree(userInfoPtr);
return userNames;
}
}
public class Program
{
public static void Main()
{
try
{
string[] userNames = LocalUserManager.GetLocalUserNames();
Console.WriteLine("Local User Names:");
foreach (string userName in userNames)
{
Console.WriteLine(userName);
}
}
catch (Exception ex)
{
Console.WriteLine("Error: " + ex.Message);
}
}
}
这段代码使用C#语言调用了NetUserEnum函数来获取本地计算机上的用户列表。通过调用LocalUserManager.GetLocalUserNames()方法,可以获取到一个包含所有本地用户账户的字符串数组。然后,可以将这些用户名打印出来或进行其他操作。
腾讯云相关产品和产品介绍链接地址:
请注意,以上链接仅供参考,具体产品选择应根据实际需求进行评估和决策。
领取专属 10元无门槛券
手把手带您无忧上云