获取Windows中的本地计算机用户名列表

时间:2011-03-09 15:13:20

标签: c# windows

如何使用C#在Windows中获取本地计算机用户名列表?

4 个答案:

答案 0 :(得分:28)

using System.Management;

SelectQuery query = new SelectQuery("Win32_UserAccount");
ManagementObjectSearcher searcher = new ManagementObjectSearcher(query);
foreach (ManagementObject envVar in searcher.Get())
{
     Console.WriteLine("Username : {0}", envVar["Name"]);
}

此代码与link KeithS posted相同。我几年前使用它没有问题,但忘记了它的来源,谢谢基思。

答案 1 :(得分:6)

我使用此代码来获取本地Windows 7用户:

public static List<string> GetComputerUsers()
{
    List<string> users = new List<string>();
    var path =
        string.Format("WinNT://{0},computer", Environment.MachineName);

    using (var computerEntry = new DirectoryEntry(path))
        foreach (DirectoryEntry childEntry in computerEntry.Children)
            if (childEntry.SchemaClassName == "User")
                users.Add(childEntry.Name);

    return users;
}

答案 2 :(得分:-2)

一种方法是列出C:\Documents and Settings中的目录(在Vista / 7中:C:\Users)。

答案 3 :(得分:-3)

以下是获取本地计算机名称的几种不同方法:

string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);