我想要一个可以在本地机器上接受任何用户名并告诉我该用户是否是管理员的功能。我尝试使用 WindowsIdentity 没有成功。现在我正在尝试使用 NetUserGetInfo。问题是它总是返回 2221。谷歌告诉我那是一个用户未找到错误。我很确定问题是我使用 null 作为服务器名。但这是在一个拥有庞大网络的工作场所。用户将在一台机器上创建帐户,并且此代码将仅在该机器上运行。那么我应该为服务器名输入什么?
[DllImport("Netapi32.dll", CharSet = CharSet.Unicode, ExactSpelling = true)]
private extern static int NetUserGetInfo(
[MarshalAs(UnmanagedType.LPWStr)] string serverName,
[MarshalAs(UnmanagedType.LPWStr)] string userName,
int level,
out IntPtr bufPtr
);
[StructLayout(LayoutKind.Sequential, CharSet = CharSet.Unicode)]
public struct USER_INFO_1
{
[MarshalAs(UnmanagedType.LPWStr)]
public string usri1_name;
[MarshalAs(UnmanagedType.LPWStr)]
public string usri1_password;
[MarshalAs(UnmanagedType.U4, SizeConst = 34)]
public string usri1_password_age;
[MarshalAs(UnmanagedType.U4, SizeConst = 34)]
public string usri1_priv;
[MarshalAs(UnmanagedType.LPWStr)]
public string usri1_home_dir;
[MarshalAs(UnmanagedType.LPWStr)]
public string usri1_comment;
[MarshalAs(UnmanagedType.U4, SizeConst = 34)]
public string usri1_flags;
[MarshalAs(UnmanagedType.LPWStr)]
public string usri1_script_path;
}
...
public static bool IsAuthorizedUser(string userId)
{
IntPtr bufPtr;
USER_INFO_1 u1 = new USER_INFO_1();
int a = NetUserGetInfo(null, userId, 1, out bufPtr);
if(a == 0)
{
u1 = (USER_INFO_1) Marshal.PtrToStructure(bufPtr, typeof (USER_INFO_1));
Console.WriteLine(u1.usri1_name);
}
else
{
Console.WriteLine("a:"+a);
}