Reputation: 143
My problem is that when I am using the Registry.SetValue I only want it to update an existing value. If a value name is entered that does not exist, I do not want to create it. I have variable data that the user enters, so I can not hardcode paths within my code.
My Code for my Set
public class SetRegistryValue : CodeActivity
{
[RequiredArgument]
public InArgument<string> kpath { get; set; }
public InArgument<string> txtName { get; set; }
[RequiredArgument]
public InArgument<string> kvaluename { get; set; }
[RequiredArgument]
public InArgument<string> kvalue { get; set; }
//This will set the value of an key that is defined by user
protected override void Execute(CodeActivityContext context)
{
string KeyPath = this.kpath.Get(context);
string KeyValueName = this.kvaluename.Get(context);
string KeyValue = this.kvalue.Get(context);
string KeyName = Path.GetDirectoryName(KeyPath);
string KeyFileName = Path.GetFileName(KeyPath);
string fullKeyPath = KeyName + "\\" + KeyFileName;
Registry.SetValue(fullKeyPath, KeyValueName, KeyValue, RegistryValueKind.String);
}
}
Upvotes: 0
Views: 1331
Reputation: 66449
Use the Registry.GetValue() method:
Retrieves the value associated with the specified name, in the specified registry key. If the name is not found in the specified key, returns a default value that you provide, or null if the specified key does not exist.
If you want to test whether the keyName
exists, test for null:
var myValue
= Registry.GetValue(@"HKEY_CURRENT_USER\missing_key", "missing_value", "hi");
// myValue = null (because that's just what GetValue returns)
If you want to test whether the valueName
exists, test for your default value:
var myValue
= Registry.GetValue(@"HKEY_CURRENT_USER\valid_key", "missing_value", null);
// myValue = null (because that's what you specified as the defaultValue)
If the path could be invalid, you could try surrounding it with a try/catch
block:
try
{
var myValue = Registry.GetValue( ... ); // throws exception on invalid keyName
if (myValue != null)
Registry.SetValue( ... );
}
catch (ArgumentException ex)
{
// do something like tell user that path is invalid
}
Upvotes: 2