How Is This Returning NULL - c#

My C# application license manager is returning NULL when checking for a Key's existence even though the key exists and my application is installed. I have tried running as an Administrator and add or removing backslashes in the Key path.
RegistryKey LitenUpKey = Registry.LocalMachine.OpenSubKey(#"SOFTWARE\LitenUp\NIT", false);
if (LitenUpKey == null) {
// Registry Key NOT Found
return false;
}
NOTE: I am building as x64!

As #RbMm pointed out, the issues was in registry reflection between 32 bit and 64 bit. The following question showed me how to choose which view I saw. Here it is.

Related

C#: Cannot see the changes in the windows registry

No error, no exception, no nothing. Everything seems to be OK, except that the registry remain as it is.
class Program
{
static void Main(string[] args)
{
try
{
Edit();
}
catch (Exception)
{
Restore(); // not included in the sample for simplicity
}
}
public static void Edit()
{
Microsoft.Win32.RegistryKey Login;
Login = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ConfigurationManager.AppSettings["Login"].ToString());
Login.SetValue("ServerName", ConfigurationManager.AppSettings["ServerName"].ToString());
Login.SetValue("ImageServerName", ConfigurationManager.AppSettings["ImageServerName"].ToString());
Login.Close();
Microsoft.Win32.RegistryKey Login2;
Login2 = Microsoft.Win32.Registry.LocalMachine.CreateSubKey(ConfigurationManager.AppSettings["Wow6432NodeLogin"].ToString());
Login2.SetValue("ServerName", ConfigurationManager.AppSettings["Wow6432NodeServerName"].ToString());
Login2.SetValue("ImageServerName", ConfigurationManager.AppSettings["Wow6432NodeImageServerName"].ToString());
Login2.Close();
}
}
I think there's is an error somewhere. But no exception is thrown. The catch block never gets hit.
I'm running it as Admin. I even ran it with no admin privileges, but still no errors when it supposed to show "access denied" or something. I restarted the laptop to see the changes applied, but still no success.
I used this code to read the recently added values and I can see the keys. But somehow the changes are not being applied.
Microsoft.Win32.RegistryKey key = Microsoft.Win32.Registry.LocalMachine.OpenSubKey(ConfigurationManager.AppSettings["Login"].ToString());
Object o = key.GetValue("ServerName");
Console.WriteLine(o.ToString());
I'm using .Net 4.5.2, building for Any CPU, SO: Windows 7.
Do I need to commit the changes or something?
As suggested by #PieterWitvoet in the comments, you might want to use OpenBaseKey() instead. This is to avoid WoW64 registry redirection as explained here: https://msdn.microsoft.com/en-us/library/windows/desktop/aa384182.aspx
Note the small print at the end of that page:
To examine the effect of running this example with regedit, inspect the values of the following keys. Note that applications should avoid using Wow6432Node in hard-coded registry paths.
So, here is an example of what you could be doing instead:
static void Edit()
{
using (var root = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64))
using (RegistryKey key = root.CreateSubKey("SOFTWARE\\Homebrew-Testing"))
{
key.SetValue("ServerName", "ServerName-Value");
key.SetValue("ImageServerName", "ImageServerName-Value");
}
}
Notice how you can ditch the second part of your code that deals specifically with Wow6432Node, which is recommended against in the article linked above.
The documentation for RegistryView states that if you request the 64-bit view on a 32-bit operating system, the returned keys will be in the 32-bit view.
I hope this helps. Best of luck.

Create registry key programmatically

I'm working on a C# project and I'm very confused about the creation of a registry key.
I have a Wix Installer. And the and of the setup File, i'm calling a custom action to create sub key (I'v try with the wix feature but it didn't work).
My custom action is :
RegistryKey Nkey = Registry.LocalMachine;
RegistryKey valkey = Nkey.OpenSubKey(Manager.REGKEY, true); //=> REGKEY = "Software\\MyService"
if (valkey == null)
{
valkey = Nkey.CreateSubKey(GestionCertificats.REGKEY);
}
valkey.Close();
Registry.LocalMachine.CreateSubKey(#"SYSTEM\CurrentControlSet\services\eventlog\Application\MyService");
After install, I can see the second key but no the first one. I'm not sure to right understand the operation of the keys. I'm working on a windows 7 64 bit, I'm compiling with "Any CPU" but my application seems to be in x86.
I've try to debug the action. value valkey is not null, but I didn't see the key with regedit. By forcing the CreateSubKey I still have no key.
I don't know what to do, I need help.
just a guess, because everything looks okay.
try closing the key returned. The description of the dispose of a key it clears resources but doesn't say it flushes it.
RegistryKey key = Registry.LocalMachine.CreateSubKey(#"SYSTEM\CurrentControlSet\services\eventlog\Application\MyService");
key.Close();

Unable to read registry: System.Security.SecurityException, Requested registry access is not allowed

I'm getting reported errors from users who are receiving the error "System.Security.SecurityException, Requested registry access is not allowed." when trying to read the registry. I can't think why someone would not have permission to read the registry and I'm unable to reproduce the problem on my Windows 7 PC. Affected users are running .NET 4.0
Here's the C# code I'm using:
var baseReg = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
var key = baseReg.OpenSubKey(RegKey, RegistryKeyPermissionCheck.ReadSubTree);
if (key != null)
{
var value = key.GetValue("DisableAutoUpdate", 0);
if (value != null)
{
updatesDisabled = Convert.ToBoolean(value);
}
}
EDIT:
I've checked permissions on the registry key concerned for the affected user and standard Users have read permission for that key.
EDIT 2 and SOLUTION:
According to the affected user, installing .NET 4.5.2 resolves the problem! I'm not sure why.
Thanks to #nozzleman's answer below this is fixed by forcing it to open the key as read-only. However it's odd that .NET 4.0 as 4.5.2 appear to behave differently.
There is an overload of the OpenSubKey(..)-Method that allows to add a third parameter. You could try passing RegistryRights.ReadKey with that one and see if that solves the issue.
baseReg.OpenSubKey(
RegKey,
RegistryKeyPermissionCheck.ReadSubTree
RegistryRights.ReadKey);
Alternatively, try the other overload accepting 2 parameters like so
baseReg.OpenSubKey(RegKey, false);
This leads to opening the subkey readonly, and you dont neet to read the whole sub tree in the given szenario..

How to retrieve the value from registry?

I want to retrieve the value from registry. For example like: HKEY_LOCAL_MACHINE\SOFTWARE\Manufacturer's name\Application name\InstallInfo
Under the 'InstallInfo' there are so many variables, like
ProductVersion, WebsiteDescription, WebSiteDirectory, CustomerName, WebSitePort etc.
I want to retrieve some values of these variables. I tried the following code but it returns
'Object reference not set to an instance of an object'
var regKey = Registry.LocalMachine;
regKey = regKey.OpenSubKey(#"SOFTWARE\ABC Limited\ABC Application\InstallInfo");
if (regKey == null)
{
Console.WriteLine("Registry value not found !");
}
else
{
string dirInfo = (string)regKey.GetValue("WebSiteDirectory");
Console.Write("WebSiteDirectory: " + dirInfo);
}
Console.ReadKey();
OpenSubKey returns null when it fails. That's clearly what's happening here.
It's failing because you are looking under the wrong root key. You are looking under HKCU but the key is under HKLM.
So you need
RegistryKey regKey = Registry.LocalMachine.OpenSubKey(
#"SOFTWARE\Manufacturer's name\Application name\InstallInfo");
You must always check the return value when you call OpenSubKey. If it is null then handle that error case.
if (regKey == null)
// handle error, raise exception etc.
The other thing to watch out for is the registry redirector. If your process is a 32 bit process running on a 64 bit system, then you will see the 32 bit view of the registry. That means that your attempt to view HKLM\Softare is transparently redirected to HKLM\Software\Wow6432Node.
Before you convert regKey.GetValue("WebSiteDirectory") to string, You should check it if it is null or not,
if (regKey.GetValue("WebSiteDirectory")!=null)
//do the rest
It may be because you are looking under wrong root key.
It should be:
Registry.CurrentUser
instead of
Registry.LocalMachine
Here you go:
Registry.LocalMachine.CreateSubKey(#"SOFTWARE\Manufacturer's name\Application name\InstallInfo");

Delete Subkey error (C#)

I have created the following registry key (copied through regedit):
HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\test
I would like to now delete this registry key, and so... I have been using the following code and am running into a small error.
RegistryKey regKey;
string regPath_Key = #"Software\Microsoft\Windows\CurrentVersion\test";
regKey = Registry.CurrentUser.OpenSubKey(regPath_Key, true);
if(regKey != null) // Always returns null, even though the key does exist.
{
Registry.CurrentUser.DeleteSubKey(regPath_Key, true);
}
The issue I am having is that the line if(regKey != null) always returns null! I have gone back and checked that the key does in fact exist multiple times - but still the same result. I am going to assume my code has issues somewhere?
Could it be that you are on a 64 bit machine and your project is set to x86 architecture? in that case, verify that the key you state exists under HKCU\Software\Wow6432Node... as every path is redirected to this 32 bit process registry...
You should not include HKEY_CURRENT_USER in the string you pass to Registry.CurrentUser.OpenSubKey(). Instead use
string regPath_Key = #"Software\Microsoft\Windows\CurrentVersion\test";

Categories