[英]c# Can't reach registry value from Windows service
I have a problem to read value from registry on my service application.我在从服务应用程序的注册表中读取值时遇到问题。 I'm new on this service application part of .NET but I was using this code on my form application.我是 .NET 的此服务应用程序部分的新手,但我在表单应用程序中使用了此代码。 There must be something different because it's not working in Service application.一定有一些不同的东西,因为它在服务应用程序中不起作用。 Anyway this is my code that I was reading normally:无论如何,这是我正常阅读的代码:
public string GetValue(string Name, string Path = "")
{
try
{
RegKey = Registry.CurrentUser.OpenSubKey(DefaultFolder + @Path + @"\");
if (RegKey != null)
{
object TempObj = RegKey.GetValue(Name);
if (TempObj == null) return "-13003";
Type T = TempObj.GetType();
if (T.IsArray)
{
string[] TempArray = (string[])TempObj;
string output = "";
for (int i = 0; i < TempArray.Length; i++)
{
output += TempArray[i].Substring(0, TempArray[i].Length - 1);
if (i != TempArray.Length) output += "\n";
}
return output;
}
else
{
return RegKey.GetValue(Name).ToString();
}
}
else
{
return "-13001";
}
}
catch (Exception ex)
{
return "-13002";
}
}
Once I change my program.cs to call my class like console application it's working again then I put this back:一旦我更改我的 program.cs 以调用我的 class 就像控制台应用程序它再次工作然后我把它放回去:
ServiceBase[] ServicesToRun;
ServicesToRun = new ServiceBase[]
{
new TestAppService()
};
ServiceBase.Run(ServicesToRun);
and it's not working.它不工作。
So far I know that RegKey variable remains null after到目前为止,我知道 RegKey 变量在之后仍然是 null
RegKey = Registry.CurrentUser.OpenSubKey(DefaultFolder + @Path + @"\");
this line but I don't know why.这条线,但我不知道为什么。
I've googled a bit and found something like this我用谷歌搜索了一下,发现了类似的东西
RegistryKey rb = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);
RegKey = rb.OpenSubKey(DefaultFolder + @"\" + Name, false);
But the result is same, my RegKey variable is still null.但是结果是一样的,我的RegKey变量还是null。
All I want is reading a value under a path like this: Computer\HKEY_CURRENT_USER\Software\ServiceReadLocation\Values我想要的只是在这样的路径下读取一个值:Computer\HKEY_CURRENT_USER\Software\ServiceReadLocation\Values
The code Registry.CurrentUser
and RegistryHive.CurrentUser
when executed in a Windows Service LocalSystem
won't work as you are expecting and is most likely the cause of null
you are encountering.在 Windows 服务LocalSystem
中执行代码Registry.CurrentUser
和RegistryHive.CurrentUser
将无法按您的预期工作,并且很可能是您遇到的null
的原因。
MSDN: MSDN:
The registry key HKEY_CURRENT_USER is associated with the default user, not the current user .注册表项 HKEY_CURRENT_USER 与默认用户相关联,而不是与当前用户相关联。 To access another user's profile, impersonate the user, then access HKEY_CURRENT_USER要访问其他用户的个人资料,请模拟该用户,然后访问 HKEY_CURRENT_USER
So I can see too options.所以我也可以看到选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.