OpenRemoteBaseKey UnauthorizedAccessException:尝试执行未经授权的操作

时间:2020-08-26 10:30:41

标签: c# wpf task

如果没有作为参数传递的terminalNumber,我想访问网络中远程PC的RegistryKeys。

    public LoginEntity(string ipAdress, string username, string password, string terminalNumber = "")
    {
        this.IpAdress = ipAdress;
        this.Username = username;
        this.Password = password;

        if (terminalNumber == "")
        {
            try
            {
                RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64);
                rKey = rKey.OpenSubKey(@"SOFTWARE\Test", RegistryKeyPermissionCheck.ReadWriteSubTree);
                var key = rKey.GetValue("terminalNumber", "NOTFOUND");

                if (key is string)
                {
                    if ((string)key != "NOTFOUND")
                        this.TerminalNumber = (string)key;
                }
            }
            catch (UnauthorizedAccessException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("UnauthorizedException: Calling TerminalNumber from Remote Registry Keys");
            }
            catch (IOException ex)
            {
                Console.WriteLine(ex.Message);
                Console.WriteLine("IOException: Remote PC not available");
            }
        }
        else
            this.TerminalNumber = terminalNumber;
    }

出于安全原因,此示例中的子项称为“测试”。

但是在 RegistryKey rKey = RegistryKey.OpenRemoteBaseKey(RegistryHive.LocalMachine, IpAdress, RegistryView.Registry64); 该应用程序引发 UnauthorizedAccessException

我做了什么:

  • 我已经以管理员身份运行Visual Studio 2019。
  • LoginEntity已在Task *中实例化。 (当我使用WPF时,我不想冻结UI,因此我在Task中运行它。)

*任务调用位于我的WPF应用程序的MainWindow()-构造函数中

Task.Run(() =>
{
     List<LoginEntity> loginUser = Utility.ReadLoginDataFromCsv(loginUserPath);
     this.Dispatcher.Invoke(() =>
     {
          Listview.ItemsSource = loginUser;
          lblUserLoading.Content = "";
      });
});
public static List<LoginEntity> ReadLoginDataFromCsv(string path, bool ignoreFirstLine = false)
{
     List<LoginEntity> list = new List<LoginEntity>();
     var lines = File.ReadAllLines(path, Encoding.UTF8);

     if (ignoreFirstLine)
          lines = lines
               .Skip(1)
               .ToArray();

     foreach (string line in lines)
     {
          var rowData = line.Split(';');
          LoginEntity le = new LoginEntity(rowData[0], rowData[1], rowData[2], rowData[3]);
          if (le.IpAdress != "" && le.Username != "" && le.Password != "")
               list.Add(le);
     }

     return list;
}

有人知道我为什么会得到UnAuthorizedException以及如何摆脱它吗?

0 个答案:

没有答案
相关问题