我在一个winform中保存了一个信息到注册表,
在windows service中,要取出这个一个值,可就是无法取到,而在winform中,用同样的方法,是可以取到。请高手指教这是为什么?怎么在windows service中访问注册表?
在windows service中,要取出这个一个值,可就是无法取到,而在winform中,用同样的方法,是可以取到。请高手指教这是为什么?怎么在windows service中访问注册表?
我的程序这样写的:
在windows Forms 一个按钮的单击事件为:
private void button1_Click(object sender, System.EventArgs e)
{
MessageBox.Show(Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\SortMsgClient\\SortMsgClient\\PathInfo").GetValue("Vip").ToString());
}
能够显示出 Vip这个项值.在 windows services 的线程中:protected override void OnStart(string[] args)
{
this.TMain=new Thread(new ThreadStart(process));
this.isRunThread =true;
this.TMain.Start();
}
/// <summary>
/// 停止此服务。
/// </summary>
protected override void OnStop()
{
this.isRunThread =false;
this.TMain.Join();
}protected void process()
{
while(this.isRunThread)
{
try{
log.Info("ok"); //log.Info(string msg) 将 msg输出到日志文件
log.Info(Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Software\\SortMsgClient\\SortMsgClient\\PathInfo").GetValue("Vip").ToString());
Thread.Sleep(1000);
}
catch
{
}
}
}
结果日记文件只产生了 含有OK 内容的日志,而从注册表中读取出来的 Vip 键值却没有产生日志,明显是没有成功读取出来。
1. 是Microsoft.Win32下的Register类,我记错了。
2. 你在catch下写条日志,会不会是public RegistryKey OpenSubKey(string name);方法产生异常了。(比如:你设置的Service启动帐户没有查看权限)
Microsoft.Win32.Registry.CurrentUser.OpenSubKey ("Software\\SortMsgClient\\SortMsgClient\\PathInfo")这打不开,结果是返回的是 null,
所以,后面的就不对了,异常的信息是未将对像实例化。我在这个windows serivce 安装程序类中指定的帐是这样的:
processInstaller.Account = ServiceAccount.LocalSystem;
难道是这里出了问题?如果是,又要怎么解决??谢谢了!
1. ArgumentNullException name 为空
2. ArgumentException 指定子项的长度大于允许的最大长度(255 个字符)。
3. ObjectDisposedException 对其调用此方法的 RegistryKey 已关闭(无法访问关闭的项)。
4. SecurityException 用户没有 RegistryPermission.SetInclude(delete, currentKey) 访问权限。 备注
必须先打开项才能用其他方法和属性对其进行操作。
如果找不到指定的子项,则返回一个空值。似乎没有你的这种异常,你的这个错误说的是类对象没有new啊!?? 不会是你的LOG函数问题吧。
建议你一步一步调试:
try
{
RegistryKey *****= Registry.LocalMachine.OpenSubKey("Software\\SortMsgClient\\SortMsgClient\\PathInfo"); //此处不要写道PathInfo子键,先写到SortMsgClient目录看看能否取到值。
String #### = *****.ToString();
}
catch(Exception error)
{
string ErrMsg = error.ToString();
}此处如果OK,那就可以排除是注册表函数操作问题啦。一步一步排除嘛,都写到一起,报的错对你也没什么具体帮助。
protected void process()
{
while(this.isRunThread)
{
try{
log.Info("ok");
Microsoft.Win32.RegistryKey subkey=Microsoft.Win32.Registry.CurrentUser.OpenSubKey("Software\\SortMsgClient\\SortMsgClient\\PathInfo");
if(subkey==null ) { log.Info("打开注册表失败!"); }
else
{
log.Info(subkey.GetValue("Vip").ToString());
} Thread.Sleep(1000);
}
catch(Exception ex)
{
log.Info(ex.Message);
}
}
}日志输入为 "打开注册表失败!",说明的确是OpenSubKey(string path)反回的是null, 打不开呀,无语,这不是windows service里是能打开的。
无语................................................ 郁闷了,莫非我人品有问题?! 惭愧啊...
问题解决了吗?我们可以共同研究解决:[email protected]