如何从C#检查本地用户帐户(即本地管理员帐户)是否处于活动状态?
我真正想要的是用“net user Administrator”命令输出“Account Active”=“Yes”(或“No”)的C#替换。
我担心这个问题看起来像是this的问题,但是我不知道要为根DirectoryEntry对象的参数传递什么。尝试过不同的东西,比如“ldap://”+ Environment.MachineName,“ldap://127.0.0.1”,“WinNT://”+ Environment.MachineName,但都没有。在所有三种情况下,我都会通过searcher.FindAll()调用抛出异常。
答案 0 :(得分:5)
class Program
{
static void Main(string[] args)
{
// Create the context for the principal object.
PrincipalContext ctx = new PrincipalContext(ContextType.Machine);
UserPrincipal u = UserPrincipal.FindByIdentity(ctx, IdentityType.SamAccountName, "Administrator");
Console.WriteLine(String.Format("Administrator is enable: {0}", u.Enabled));
}
}
答案 1 :(得分:1)
您可以查询WMI的Win32_UserAccount
这是两个MS的 wmi代码创建者作为参考发布的样板;
using System;
using System.Management;
using System.Windows.Forms;
namespace WMISample
{
public class MyWMIQuery
{
public static void Main()
{
try
{
ManagementObjectSearcher searcher = new ManagementObjectSearcher("root\\CIMV2", "SELECT Disabled FROM Win32_UserAccount WHERE name = 'alexk'");
foreach (ManagementObject queryObj in searcher.Get())
{
Console.WriteLine("-----------------------------------");
Console.WriteLine("Win32_UserAccount instance");
Console.WriteLine("-----------------------------------");
Console.WriteLine("Disabled: {0}", queryObj["Disabled"]);
Console.ReadKey();
}
}
catch (ManagementException e)
{
MessageBox.Show("An error occurred while querying for WMI data: " + e.Message);
}
}
}
}
(我会链接工具,但像往常一样msdn链接已经死了)
答案 2 :(得分:1)
试试这个。
var server = "YOURMACHINENAME";
var username = "Guest";
var de = new DirectoryEntry {Path = "WinNT://" + server + ",computer"};
var result = de.Children
.Cast<DirectoryEntry>()
.First<DirectoryEntry>(d => d.SchemaClassName == "User" && d.Properties["Name"].Value.ToString() == username);
var flags = (int)result.Properties["UserFlags"].Value;
var disabled = (flags & 2) == 2;
答案 3 :(得分:0)
This并不完全相同,但他们使用DirectoryEntry directoryEntry = new DirectoryEntry(string.Format("WinNT://{0}/{1}", computerName, username));
会有帮助吗?
答案 4 :(得分:0)
考虑到它是本地用户,您需要调用win32 api功能NetGetUserInfo来获取所需内容。
pinvoke.net中的示例几乎是您所需要的,但是您需要将level参数更改为2才能获得neccesary info