12shadow12 12shadow12 - 19 days ago 9
C# Question

Set RegistryValueKind from a method param

I'm trying to set RegistryValueKind with a parameter from a method but this is not working, it looks like it can't be set from a parameter. Is there a way to get around this?

static bool TrySetKey(string Dir, string Value, string Data, string ValueKind)
{
if (!CanReadKey(Dir))
return false;
using (RegistryKey RegKey = Registry.LocalMachine.OpenSubKey(Dir, true))
if (RegKey == null)
return false;
RegKey.SetValue(Value, Data, RegistryValueKind.ValueKind);
return true;
}
}


Solution: I should mention that I changed the string parameter for Data to an Object so I can pass different values.

static bool TrySetKey(string Value, Object Data, RegistryValueKind ValueKind)
{
// code here
RegKey.SetValue(Value, Data, ValueKind);
return true;
}

TrySetKey("Value Name", "1", RegistryValueKind.DWord)

Answer

RegistryValueKind is an enum, So you cannot take its value from string, better to Change your method signature like the following:

static bool TrySetKey(string Dir, string Value, string Data, RegistryValueKind ValueKind)
{
   // code here 
   // and set value like this
     RegKey.SetValue(Value, Data, ValueKind);
   return true;
}

So that you can call this method like this :

TrySetKey("Value Name", "1", RegistryValueKind.DWord)
Comments