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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/485341/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-15 11:53:38  来源:igfitidea点击:

In VB.NET, how do you get a list of all users in the current Windows machine?

.netwindowsvb.net

提问by Kingamoon

In VB.NET, how do you get a list of all users in the current Windows machine?

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

回答by Nathan W

You can use the registry which requires a little bit of parsing but hey it works. Here is some code:

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

C#

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

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

回答by dsrdakota

Here's an improved version of Nathan W'sanswer:

这是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

This function returns a list of all users on the current domain/machine from the registry. For his answer, it doesn't recognize the Guest account on my system. Don't know why.

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