【发布时间】:2023-04-03 21:10:02
【问题描述】:
如何使用 C# 在 windows 中获取本地计算机用户名列表?
【问题讨论】:
如何使用 C# 在 windows 中获取本地计算机用户名列表?
【问题讨论】:
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 相同。几年前我使用它没有问题,但忘记了它的来源,谢谢 Keith。
【讨论】:
我使用此代码获取本地 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;
}
【讨论】:
一种方法是列出C:\Documents and Settings 中的目录(在Vista/7 中:C:\Users)。
【讨论】:
以下是获取本地计算机名称的几种不同方法:
string name = Environment.MachineName;
string name = System.Net.Dns.GetHostName();
string name = System.Windows.Forms.SystemInformation.ComputerName;
string name = System.Environment.GetEnvironmentVariable(“COMPUTERNAME”);
【讨论】: