Registry Editing: NullReferenceException driving me crazy. Please help me out...

M

Markali A.

Hello,

I'm absolutely new to programming, so please don't be too hard on me...

I'm trying to make a simple form application to hide or show hidden
files. When I try to run the application I get a
"System.NullReferenceException: Object reference not set to an instance
of an object."
I found many topics related to this problem, but I still cannot figure
it out.

Here's the code:

partial class Form1 : Form

{
public Form1()
{
InitializeComponent();
}

private void HideFiles()
{
RegistryKey MyKey = Registry.CurrentUser;
MyKey =
MyKey.OpenSubKey(".Software\\Microsoft\\Windows\\CurrentVersion\\Explore
r\\Advanced", true);
MyKey.SetValue("Hidden",2);
MyKey.Close();
}

private void ShowFiles()
{
RegistryKey MyKey;
MyKey = Registry.CurrentUser;
MyKey =
MyKey.OpenSubKey(".Software\\Microsoft\\Windows\\CurrentVersion\\Explore
r\\Advanced", true);
MyKey.SetValue("Hidden",1);
MyKey.Close();
}

private void ShowButton_Click(object sender, EventArgs e)
{
ShowFiles();
}

private void HideButton_Click(object sender, EventArgs e)
{
HideFiles();
}


}
 
M

Morten Wennevik

Hi Markali,

Don't worry, we all have experienced this error and do so still :)
The error means you have an reference that is null and you try to do
something with it.

I suspect it is the ...

RegistryKey MyKey

.... part. OpenSubKey returns null when it fails to aquire the subkey, so
when you try to do ...

MyKey.SetValue("Hidden",2);
MyKey.Close();

.... it will choke.

put something like this in the method

if(MyKey != null)
{
MyKey.SetValue("Hidden",2);
MyKey.Close();
}
 
G

Guest

Hi,
Morten is right.

".Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced" should
be "Software\\Microsoft\\Windows\\CurrentVersion\\Explorer\\Advanced".

All the Best,
Phil.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Top