注册表:搜索已知的字符串值并返回其所在的SubKey的名称

时间:2013-12-06 18:07:01

标签: vb.net registry

我正在为一个孤立的环境开发一个自动化应用程序。其功能之一是从注册表路径HKLM \ Software \ Microsoft \ Windows NT \ CurrentVersion \ ProfileList \

自动清除Windows用户配置文件

我遇到的麻烦在于如何确定我正在删除正确的子密钥,因为此路径下的每个子密钥都是神秘的。通过打开每个子项并检查我正在寻找的字符串值(ProfileImagePath = C:\ Users \ USERANME),我可以在regedit中直观地识别正确的子键。

示例:子键= S1-5-21-420551719-245851362-9522986-177556

包含字符串值= ProfileImagePath = C:\ Users \ n9000988

我已经有一个查找和查找所有可用用户名的函数,然后是一个用户控件来选择要使用的用户名。

因此,在此示例中,定义并选择了n9000988。

所以现在我只需要能够定义stringvalue所在的子键。一旦我有了,我就可以调用删除子键,因为这是该子目标的最终目标。

到目前为止我尝试过:

For Each subKeyName As String In My.Computer.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList").GetSubKeyNames()
        For Each profPath As String In My.Computer.Registry.LocalMachine.OpenSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & subKeyName).GetValue("ProfileImagePath")
            MsgBox(profPath)
        Next
    Next

但是,对于包含字符串ProfileImagePath的所有子键,这将为ProfileImagePath中的每个字符返回一个MsgBox。

我几乎觉得我在这个子系统中的逻辑试图向前走太远,然后才能确定如何获取子项的名称。

这个让我的大脑受伤。任何帮助将不胜感激。

更新: 那很完美,很干净! 最终结果 -

Public Class Dialog3

Private Function Username_To_SID(ByVal Username As String) As String
    Return New Security.Principal.NTAccount(Username).Translate(GetType(Security.Principal.SecurityIdentifier)).Value
End Function


Private Sub OK_Button_Click(ByVal sender As System.Object, ByVal e As System.EventArgs) Handles OK_Button.Click

    ' Kill SearchIndexer to release locked files
    Try
        Process.GetProcessesByName("SearchIndexer")(0).Kill()
    Catch ex As Exception
    End Try

    Dim userID As String = Dialog1.ListBox1.SelectedItem
    Dim userPath As String = "C:\users\" & userID

    ' Rename user folder
    Try
        My.Computer.FileSystem.RenameDirectory(userPath, userID & ".BAK")
    Catch ex As Exception
        MsgBox("Failed to rename user folders path")
    End Try

    Try
        My.Computer.Registry.LocalMachine.DeleteSubKey("Software\Microsoft\Windows NT\CurrentVersion\ProfileList\" & (Username_To_SID(Dialog1.ListBox1.SelectedItem)))

    Catch ex As Exception
        MsgBox("Failed to remove registry entry in ProfileList")

    End Try

    Me.DialogResult = System.Windows.Forms.DialogResult.OK
    Dialog1.Close()
    Me.Close()
End Sub

1 个答案:

答案 0 :(得分:1)

我建议您在使用.NET编程时停止使用/搜索/解析注册表技术,您可以使用纯.NET代码完成所有操作。

如果我想知道你想要的是知道用户名的等效SID,那么你可以使用它:

' [ Username To SID ]
'
' // By Elektro H@cker
'
' Usage Examples:
' MsgBox(Username_To_SID("Administrator")) ' Result like: S-1-5-21-250596608-219436059-1115792336-500

''' <summary>
''' Returns the SecurityIdentifier of an existing Username.
''' </summary>
''' <param name="Username">Indicates the username to retrieve the SID.</param>
Private Function Username_To_SID(ByVal Username As String) As String

    Return New Security.Principal.NTAccount(Username).
               Translate(GetType(Security.Principal.SecurityIdentifier)).Value

End Function
相关问题