繁体   English   中英

c# 无法从 Windows 服务达到注册表值

[英]c# Can't reach registry value from Windows service

我在从服务应用程序的注册表中读取值时遇到问题。 我是 .NET 的此服务应用程序部分的新手,但我在表单应用程序中使用了此代码。 一定有一些不同的东西,因为它在服务应用程序中不起作用。 无论如何,这是我正常阅读的代码:

 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";
        }
    }

一旦我更改我的 program.cs 以调用我的 class 就像控制台应用程序它再次工作然后我把它放回去:

ServiceBase[] ServicesToRun;
            ServicesToRun = new ServiceBase[]
            {

                new TestAppService()
            };
            ServiceBase.Run(ServicesToRun);

它不工作。

到目前为止,我知道 RegKey 变量在之后仍然是 null

RegKey = Registry.CurrentUser.OpenSubKey(DefaultFolder + @Path + @"\");

这条线,但我不知道为什么。

我用谷歌搜索了一下,发现了类似的东西

RegistryKey rb = RegistryKey.OpenBaseKey(RegistryHive.CurrentUser, RegistryView.Default);
RegKey = rb.OpenSubKey(DefaultFolder + @"\" + Name, false);

但是结果是一样的,我的RegKey变量还是null。

我想要的只是在这样的路径下读取一个值:Computer\HKEY_CURRENT_USER\Software\ServiceReadLocation\Values

在 Windows 服务LocalSystem中执行代码Registry.CurrentUserRegistryHive.CurrentUser将无法按您的预期工作,并且很可能是您遇到的null的原因。

MSDN:

注册表项 HKEY_CURRENT_USER 与默认用户相关联,而不是与当前用户相关联。 要访问其他用户的个人资料,请模拟该用户,然后访问 HKEY_CURRENT_USER

所以我也可以看到选项。

  1. 可以说最简单的方法是以该用户身份运行服务
  2. 以 LocalSystem 身份运行服务并模拟用户,然后在需要时访问注册表。 阅读后,您可以停止冒充。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM