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

ghg1uchk  于 2023-04-08  发布在  .NET
关注(0)|答案(3)|浏览(198)

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

fwzugrvs

fwzugrvs1#

你可以使用注册表,这需要一点解析,但它工作正常。下面是一些代码:

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
tmb3ates

tmb3ates2#

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

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帐户。不知道为什么。

7lrncoxx

7lrncoxx3#

Windows 11 True今天的工作原理:

Private Function GetLocalUsers() As List(Of String)
    Dim OpenCMD
    OpenCMD = CreateObject("wscript.shell")
    OpenCMD.run("cmd /C wmic useraccount list full | clip", 0)
    System.Threading.Thread.Sleep(1000)

    Dim result As String = Clipboard.GetText()
    Dim lines() As String = result.Split({vbCrLf, vbCr, vbLf}, StringSplitOptions.None)
    For Each linea As String In lines
        If Mid(linea, 1, 5) = "Name=" Then
            ComboBox1.Items.Add(Mid(linea, 6, linea.Length))
        End If
    Next

    Return Nothing
End Function

相关问题