gpt4 book ai didi

ruby Win32 注册表 : The system cannot find the file specified when looking for registry key that doesn't exist

转载 作者:太空宇宙 更新时间:2023-11-03 16:02:06 24 4
gpt4 key购买 nike

我正在编写一个 ruby​​ 函数以从给定的 DisplayName 获取 UninstallString。我的函数只有在我给它一个现有的 DisplayName 来查找时才能成功运行,当我给它一个不存在的东西时它会崩溃。我不确定在什么条件下检查哪个变量(无?空?)所以我可以向我的脚本抛出异常打印一条消息“未找到”而不是崩溃?

require 'win32/registry'

def get_uninstallstring(app_name)

paths = [ "Software\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"Software\\Wow6432Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall",
"Software\\Wow6464Node\\Microsoft\\Windows\\CurrentVersion\\Uninstall" ]
access_type = Win32::Registry::KEY_ALL_ACCESS

paths.each do |path| # This is line 9
Win32::Registry::HKEY_LOCAL_MACHINE.open(path, access_type) do |reg|
reg.each_key do |key|
k = reg.open(key)
app = k['DisplayName'] rescue nil
if app == app_name
str = k['UninstallString'] rescue nil
return str
end
end
end
end
return false
end

puts get_uninstallstring("ABC") # This is line 24

这是错误输出:

C:/ruby/1.9.1/win32/registry.rb:385:in `open': The system cannot find the file specified. (Win32::Registry::Error)
from C:/heliopolis/opscode/chef/embedded/lib/ruby/1.9.1/win32/registry.rb:496:in `open'
from test.rb:10:in `block in get_uninstallstring'
from test.rb:9:in `each'
from test.rb:9:in `get_uninstallstring'
from test.rb:24:in `<main>'

最佳答案

所以我自己找到了解决办法。在我真正获得它的值之前,我不得不编写另一个函数来检查给定路径中是​​否存在该键。

def key_exists?(path)
begin
Win32::Registry::HKEY_LOCAL_MACHINE.open(path, ::Win32::Registry::KEY_READ)
return true
rescue
return false
end
end

这里是修改后的 get 函数:

  paths.each do |path| 
if key_exists?(path)
Win32::Registry::HKEY_LOCAL_MACHINE.open(path, access_type) do |reg|
reg.each_key do |key|
k = reg.open(key)
app = k['DisplayName'] rescue nil
if app == app_name
return k['UninstallString'] rescue nil
end
end
end
else
return false
end
end

关于 ruby Win32 注册表 : The system cannot find the file specified when looking for registry key that doesn't exist,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22393572/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com