在VB.NET中,如何获取当前Windows机器中所有用户的列表?

时间:2009-01-27 21:28:31

标签: .net windows vb.net

在VB.NET中,如何获取当前Windows机器中所有用户的列表?

2 个答案:

答案 0 :(得分:1)

您可以使用需要稍微解析的注册表,但它可以工作。这是一些代码:

<强> C#

 RegistryKey userskey = Registry.LocalMachine.OpenSubKey(@"SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList");
        foreach (string keyname in userskey.GetSubKeyNames())
        {
                using (RegistryKey key = userskey.OpenSubKey(keyname))
                {
                    string userpath = (string)key.GetValue("ProfileImagePath");
                    string username = System.IO.Path.GetFileNameWithoutExtension(userpath);
                    Console.WriteLine("{0}", username);
                }
        }

<强> VB

Dim userskey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList")
For Each keyname As String In userskey.GetSubKeyNames()
    Using key As RegistryKey = userskey.OpenSubKey(keyname)
        Dim userpath As String = DirectCast(key.GetValue("ProfileImagePath"), String)
        Dim username As String = System.IO.Path.GetFileNameWithoutExtension(userpath)
        Console.WriteLine("{0}", username)
    End Using
Next

答案 1 :(得分:0)

以下是Nathan W's答案的改进版本:

Function GetUsers() As List(Of String)
    Dim ret As New List(Of String)
    Dim userskey As RegistryKey = Registry.LocalMachine.OpenSubKey("SOFTWARE\Microsoft\Windows NT\CurrentVersion\ProfileList")
    For Each keyname As String In userskey.GetSubKeyNames()
        Using key As RegistryKey = userskey.OpenSubKey(keyname)
            Dim userpath As String = DirectCast(key.GetValue("ProfileImagePath"), String)
            Dim username As String = System.IO.Path.GetFileNameWithoutExtension(userpath)
            'Console.WriteLine("{0}", username)
            ret.Add(username)
        End Using
    Next
    If Not ret.Contains("Guest") Then ret.Add("Guest")
    ret.Sort()

    Return ret
End Function

此函数从注册表返回当前域/机器上所有用户的列表。对于他的回答,它无法识别我系统上的Guest帐户。不知道为什么。