简体   繁体   中英

Not able to set a registry value in C#

I have a windows form app called system_module . And I want it to startup with windows. Here is my code for that.

private void Form1_Load(object sender, EventArgs e)
    {

        string keyName = @"Software\\Microsoft\\Windows\\CurrentVersion\\Run";
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(keyName, true))
        {
            if (key == null)
            {
                // Key doesn't exist.
                key.SetValue("system_module", "Application Location");
            }
            else { }
        }
    }

But this is not creating a value in run/ I have searched the whole registry and found nothing referring to system_module except some irrelevant values.

PS I do not know much about registry things. Sorry if my terminology is wrong. Hope you understand what I am trying to to. I found the above code in some other question in this site. I don't know why this is not working.

You are not using the SetValue() - because the "Run"-Key exists

use:

if (key != null)
        {
            // Key doesn't exist.
            key.SetValue("system_module", "Application Location");
        }

and handle the key == null too to add the Run key (by default this key exists)

if you dont want to modify the key if your "system_module","Application Location" already exists you have to query the values beneath the "key"

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM