我有一个从"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU".输出各种注册表值的程序
但是,程序在GetValue部分或程序的s变量处输出错误,无法隐含地将类型“‘object”转换为“string”!并且程序输出"Cannot access a closed registry key too“的错误。
有没有人能给我一些关于代码的建议?谢谢!
代码:
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using Microsoft.Win32;
namespace RegKeys
{
class ConsoleApplication1
{
static void Main(string[] args)
{
try
{
RegistryKey rk = Registry.CurrentUser;
rk = rk.OpenSubKey(@"Software\Microsoft\Windows\CurrentVersion\Explorer\ComDlg32\LastVisitedMRU", false);
PrintKeys(rk);
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
}
static void PrintKeys(RegistryKey rk)
{
if (rk == null)
{
Console.WriteLine("No specified registry key!");
return;
}
String[] names = rk.GetValueNames();
Console.WriteLine("Subkeys of " + rk.Name);
Console.WriteLine("-----------------------------------------------");
foreach (String s in names)
{
try
{
if (s == "MRUList")
{
continue;
}
else
{
String val = rk.GetValue(s);
Console.WriteLine(s + " Contains the value of : " + val);
}
rk.Close();
}
catch (Exception MyError)
{
Console.WriteLine("An error has occurred: " + MyError.Message);
}
Console.WriteLine("-----------------------------------------------");
rk.Close();
}
}
}
}发布于 2010-12-06 15:39:15
除了Matti的建议之外,我们也不清楚为什么要查看所有的子值。为什么不直接买你想要的呢?如下所示:
using System;
using Microsoft.Win32;
class Test
{
static void Main()
{
using (var key = Registry.CurrentUser.OpenSubKey
(@"Software\Microsoft\Windows\CurrentVersion\" +
@"Explorer\ComDlg32\LastVisitedMRU", false))
{
string value = (string) key.GetValue("MRUList");
Console.WriteLine(value);
}
}
}(请注意using语句,以确保始终关闭注册表项。)
当然,您可能还想进行一些测试,以确保键和值存在。
发布于 2010-12-06 15:33:33
这里有一些关于代码的建议:
GetValue返回一个object,而不是一个string。您需要将其强制转换为string,或者对其调用ToString (如果您知道它实际上是一个字符串,请始终使用前者)。
发布于 2010-12-06 15:34:03
如果你确定预期的结果是字符串,只需对其进行类型转换。
String val = (String) rk.GetValue(s);
//or
String val = rk.GetValue(s) as String;https://stackoverflow.com/questions/4364134
复制相似问题