在Ruby中创建和编辑reg键

时间:2015-02-04 02:50:11

标签: ruby registry

我正在尝试在ruby中创建和编辑一个reg键,但不断收到以下错误:

setKeyStringValue error:
false
error in 'open' system cannot find file specified

我的代码:

require 'win32/registry' 

$hkey_local_machine=Win32::Registry::HKEY_LOCAL_MACHINE 
$hkey_current_user=Win32::Registry::HKEY_CURRENT_USER  

# Returns the Microsoft Registry path to the Microsoft software information 
def getKeyValue(hive, key_path, key_name) 
  reg_obj=hive.open(key_path, Win32::Registry::KEY_READ) 
  begin 
          reg_typ, reg_val = reg_obj.read(key_name) 
   rescue Win32::Registry::Error 
          puts "key not found : #{key_name}" 
    end 
    return reg_val 
end 

#used to set a String value for a key 
def setKeyStringValue(hive,key_path, key_name, key_value) 
begin
    reg_key=hive.open(key_path, Win32::Registry::KEY_WRITE) 
    puts "opened key"
    reg_key.write(key_name,Win32::Registry::REG_SZ,key_value) 
rescue Win32::Registry::Error 
    puts "setKeyStringValue error:"
    return false
end 
return true
end 

puts setKeyStringValue(Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\PsychSoft","foo","woo")

puts getKeyValue(Win32::Registry::HKEY_CURRENT_USER,"SOFTWARE\\PsychSoft","foo")

有人可以解释为什么这段代码不起作用?

1 个答案:

答案 0 :(得分:0)

我认为您的注册表路径需要单独包含在内 你的代码就是这样的

profiles_key = 'Software\Microsoft'

puts setKeyStringValue(Win32::Registry::HKEY_CURRENT_USER, profiles_key, "foo", "woo")

puts getKeyValue(Win32::Registry::HKEY_CURRENT_USER, profiles_key, "foo")

哪个给出了

opened key
true
woo