0

我的问题是,当我使用 Registry.SetValue 时,我只希望它更新现有值。如果输入的值名称不存在,我不想创建它。我有用户输入的可变数据,所以我不能在我的代码中硬编码路径。

我的套装代码

    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);
    }
}
4

1 回答 1

2

使用Registry.GetValue()方法:

在指定的注册表项中检索与指定名称关联的值。如果在指定的键中找不到名称,则返回您提供的默认值,如果指定的键不存在,则返回 null。

如果要测试是否keyName存在,请测试null:

var myValue
  = Registry.GetValue(@"HKEY_CURRENT_USER\missing_key", "missing_value", "hi");

// myValue = null (because that's just what GetValue returns)

如果要测试是否valueName存在,请测试您的默认值:

var myValue
  = Registry.GetValue(@"HKEY_CURRENT_USER\valid_key", "missing_value", null);

// myValue = null (because that's what you specified as the defaultValue)

如果路径可能无效,您可以尝试用try/catch块包围它:

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
}
于 2013-11-01T21:21:15.907 回答