Search code examples
c#filelistboxregistry

How to delete a registrykey when selecting on listbox?


I have added all startup programs to a listbox. How can I delete the selected registry key when I select the item and click on a button?

Listbox code:

    private void starting()
    {
        RegistryKey HKCU = Registry.CurrentUser.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
        {
            foreach (string Programs in HKCU.GetValueNames())
            {
                startupinfo.Items.Add(Programs);
            }
            HKCU.Close();
        }
        RegistryKey HKLM = Registry.LocalMachine.OpenSubKey("Software\\Microsoft\\Windows\\CurrentVersion\\Run");
        {
            foreach (string HKLMPrograms in HKLM.GetValueNames())
            {
                startupinfo.Items.Add(HKLMPrograms);
            }
            HKLM.Close();
        }

This the startup folder that I can delete file by file: (Thanks Rikki-B for helping me)

    private void readfiles()
    {
        string startfolder = Environment.GetFolderPath(Environment.SpecialFolder.Startup);

        var files = Directory.GetFiles(startfolder).Where(name => !name.EndsWith(".ini"));

        foreach (string file in files)
        {
            startupinfo.Items.Add(System.IO.Path.GetFileName(file));
            startupinfoDict.Add(System.IO.Path.GetFileName(file), file);
        }
    }

this is the button :

    private void DisableBtn_Click(object sender, RoutedEventArgs e)
    {
        if (startupinfo.SelectedItem != null)
    {
        string s = startupinfo.SelectedItem.ToString();

        if (startupinfoDict.ContainsKey(s))
        {
            File.Delete(startupinfoDict[s]);
        }
    }
}

How listbox looks like:

1


Solution

  • Try this out.

    private void DisableBtn_Click(object sender, RoutedEventArgs e)
    {
        if (startupinfo.SelectedItem != null)
        {
            string s = startupinfo.SelectedItem.ToString();
    
            if (startupinfoDict.ContainsKey(s))
            {
                try
                {
                    File.Delete(startupinfoDict[s]);
                }
                catch
                {
                    //errors are here
                }
            }
    
            string keyName = @"Software\Microsoft\Windows\CurrentVersion\Run";
            using (Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.CurrentUser.OpenSubKey(keyName, true))
            {
                if (key != null)
                {
                    try
                    {
                        key.DeleteValue(startupinfo.SelectedItem.ToString());
                    }
                    catch
                    {
                        //errors are here
                    }
                }
            }
        }
    }