RegistryKey.SetValue throws System.IO.IOException: The handle is invalid.

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

I'm getting and setting a registry value and occasionally I get

System.IO.IOException: The handle is invalid

The stack trace shows
at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str
at Microsoft.Win32.RegistryKey.SetValue(String name, Object value
at Gargoyle.Middleware.Util.RegistryHelper.SetValue(String valueName, Object newValue

Any idea what could cause this?
 
Philip Martin said:
I'm getting and setting a registry value and occasionally I get:

System.IO.IOException: The handle is invalid.

The stack trace shows:
at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
at Microsoft.Win32.RegistryKey.SetValue(String name, Object value)
at Gargoyle.Middleware.Util.RegistryHelper.SetValue(String valueName, Object newValue)

Any idea what could cause this?

Could you post a short but complete program which demonstrates the
problem?

See http://www.pobox.com/~skeet/csharp/complete.html for details of
what I mean by that.
Could you post your code?
 
I could but it wouldn't help because I can't produce the error outside of production. I'm not getting a Null Reference exception so I know that the RegistryKey has be created. I use RegistryKey.OpenSubKey to get the RegistryKey. I immediately check to see if the key returned is not null. I'm at a loss since there doesn't seem to be anything in the docs that reference the System.IO.Exception getting thrown when trying to set a registry ke
 
Philip said:
I'm getting and setting a registry value and occasionally I get:

System.IO.IOException: The handle is invalid.

The stack trace shows:
at Microsoft.Win32.RegistryKey.Win32Error(Int32 errorCode, String str)
at Microsoft.Win32.RegistryKey.SetValue(String name, Object value)
at Gargoyle.Middleware.Util.RegistryHelper.SetValue(String valueName, Object newValue)

Something is deleting the key from under your RegistryKey object. This
code will demonstrate the exception (insert standard disclaimer for the
dangers of code that modifies the Registry):

RegistryKey softwareKey = Registry.CurrentUser.OpenSubKey(
"Software", true);
RegistryKey writeKey;

if (softwareKey != null) {
softwareKey.CreateSubKey( "mikeb");
writeKey = softwareKey.OpenSubKey( "mikeb", true);

if (writeKey != null){
softwareKey.DeleteSubKey( "mikeb");
writeKey.SetValue( "test", 1);
}
}
 
Any idea what could cause this?

If this happens for a RegistryKey object that isn't used (and
therefore eligible for garbage collection) after the SetValue call,
this could be caused by premature garbage collection (see KB 309327).
The workaround in that case is either to use GC.KeepAlive as described
in the KB article, or better yet to call Close afterwards (or use a
using block so Dispose is called).



Mattias
 
Back
Top