Windows Form Project c#, checking if Key exist in Registry

Gennady Gurin 81 Reputation points
2024-12-12T23:44:37.34+00:00

Hi, I tried various things does not seem to work if key does not exist it gives exceptional error, but if it does it works.

Here Code:

private void Form1_Load(object sender, EventArgs e)

{

  

    RegistryKey Key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MyApp") ;

   

 if (Key == null) Activated_Bool = false;  //key exist

    

    else Activated_Bool = true;

    

Key.Close();

}

Anyone has any idea, thanks in advance.

Windows Forms
Windows Forms
A set of .NET Framework managed libraries for developing graphical user interfaces.
1,915 questions
C#
C#
An object-oriented and type-safe programming language that has its roots in the C family of languages and includes support for component-oriented programming.
11,157 questions
0 comments No comments
{count} votes

Accepted answer
  1. Jiale Xue - MSFT 48,441 Reputation points Microsoft Vendor
    2024-12-13T08:07:02.4566667+00:00

    Hi @Gennady Gurin , Welcome to Microsoft Q&A,

    You're trying to call Key.Close() regardless of whether Key is null.

    If the registry key doesn't exist (Key == null), attempting to call Key.Close() will result in a NullReferenceException.

    private void Form1_Load(object sender, EventArgs e)
    {
        // Attempt to open the registry key
        using (RegistryKey key = Registry.CurrentUser.OpenSubKey(@"SOFTWARE\MyApp"))
        {
            // Check if the key exists
            if (key == null)
            {
                Activated_Bool = false; // Key does not exist
            }
            else
            {
                Activated_Bool = true; // Key exists
            }
        } // The 'using' statement ensures the key is properly closed
    }
    

    Best Regards,

    Jiale


    If the answer is the right solution, please click "Accept Answer" and kindly upvote it. If you have extra questions about this answer, please click "Comment". 

    Note: Please follow the steps in our documentation to enable e-mail notifications if you want to receive the related email notification for this thread.

    1 person found this answer helpful.

0 additional answers

Sort by: Most helpful

Your answer

Answers can be marked as Accepted Answers by the question author, which helps users to know the answer solved the author's problem.