How to retrieve the value from registry? - c#

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

Related

How Is This Returning NULL

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.

How to delete registry key: getting error "Cannot delete... because the subkey does not exist"

To begin, I recognize that this question appears similar to others. However, my research thus far has not found a solution to the specific problem I am facing, just a lot of solutions to problems with similar circumstance.
I am new to registry functions, so I've been using a VM to mess around with them and see what I can do. Currently, I am trying to test the creation, reading, and subsequent deletion of a subKey and HKEY_CURRENT_USER. At the moment, I can do everything in that list except deletion. The relevant code is as follows:
//This first sample will attempt to create a test key under HKEY_CURRENT_USER
Console.WriteLine("Creating subkey under HKEY_CURRENT_USER");
RegistryKey testKey2 = Registry.CurrentUser.CreateSubKey("SubKeyTester");
Console.WriteLine("testKey2 is now assigned to {0}", testKey2);
//This ensures that testKey2 is the value that I think it is
Console.WriteLine("testKey2 value = {0}\n", testKey2);
with an output of:
Beginning test...
Creating subkey under HKEY_CURRENT_USER
testKey2 is now assigned to HKEY_CURRENT_USER\SubKeyTester
testKey2 value = HKEY_CURRENT_USER\SubKeyTester
Notably, testKey2 has stored "HKEY_CURRENT_USER\SubKeyTester" rather than the "SubKeyTester" that I expected.
After this, I'm able to check the subkeys under HKEY_CURRENT_USER and verify that yes, "SubKeyTester" is indeed present among the CurrentUser subkeys. Now, I just need to delete it. My code is as follows:
//This portion of the test will attempt to delete SubKeyTester from
//HKEY_CURRENT_USER
Console.WriteLine("Attempting to delete test subkey\n");
try
{
Registry.CurrentUser.DeleteSubKeyTree(testKey2.ToString());
Console.WriteLine("Target has been deleted\n");
}
catch(Exception e)
{
Console.WriteLine("The key targeted for deletion... is not found.\nError: {0}\n", e);
}
//Another safety check to verify that only SubKeyTester has been deleted
Console.WriteLine("There are {0} subkeys under {1}.",
Registry.CurrentUser.SubKeyCount.ToString(), Registry.CurrentUser.Name);
foreach (string subKeyName in Registry.CurrentUser.GetSubKeyNames())
Console.WriteLine(subKeyName);
testKey2.Close();
The output informs me:
"Error: System.ArgumentException: Cannot delete a subkey tree because the subkey does not exist."
It then lists all the subkeys under HKEY_CURRENT_USER, which still includes the testKey "SubKeyTester".
I believe the problem could be solved by just hard-coding the path to that subkey in the DeleteSubKeyTree call, but I want to avoid that. I'd rather just be able to invoke testKey2 as a parameter and delete the key that way. Is there a way to do that?
I have found my error, and I was on the right track. The correct code is as follows:
Console.WriteLine("Creating subkey under HKEY__CURRENT_USER\n");
const string testKey2 = "SubKeyTester";
Registry.CurrentUser.CreateSubKey(testKey2);
This way, testKey2 is always "SubKeyTester". Then, the only other alteration needed is to the delete function's parameter.
Registry.CurrentUser.DeleteSubKeyTree(testKey2);
removing the ToString() method.
I believe the problem was as I said, that testKey2 was getting "HKEY_CURRENT_USER//SubKeyTester" instead of just "SubKeyTester". But this way, testKey2 only gets "SubKeyTester", which allows for a correct filepath to the appropriate key.
I had tried using
Registry.DeleteSubKeyTree(testKey2.ToString());
to get around the pathing error, but "Registry" does not have a DeleteSubKeyTree method, so that simply didn't work.
Also, this solution does not require a .close() statement, because no key was ever opened.
Not a solution, but I found the error message is a red herring.
One of the subkeys had permissions preventing it from being deleted.
Confirmed in Registry Editor too:

How to write to HKLM without WOW redirection in WOW scenario?

I have a WOW scenario and want to change the value of Key at
HKLM\Software\Microsoft\ABCD\
I am using this code :
String key = #"SOFTWARE\Microsoft\ABCD\";
RegistryKey reg64key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
RegistryKey reg_64bit_Name = reg64key.OpenSubKey(key);
reg_64bit_Name.SetValue("Name","ahsan");
However this is not working. Can anyone kindly suggest what I need to do here ?
NB:
1. Not working means I am getting the following exception while running the app :
System.NullReferenceException: Object reference not set to an instance of an object.
Firstly, by "this is not working" can you please describe any error messages, exceptions compiler errors?
That being said your code has
reg64key.SetValue("Key","ahsan");
Where you will see you are using the "Key" (as a string). Trying changing this to.
reg64key.SetValue(key,"ahsan");
So you are using your variable instead of the string "Key"
EDIT: After OP changed
After your edits I went back and tried this for myself. Please see the code below (this is tested)
RegistryKey reg64key = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64);
String key = #"SOFTWARE\Microsoft\ABCD";
if (reg64key == null)
throw new Exception("reg64key");
var basekey = reg64key.OpenSubKey(key);
if (basekey == null)
basekey = reg64key.CreateSubKey(key);
basekey.SetValue("Name", "ahsan");
You will see from the code the first thing we do is grab the reg64key for HKLM. Next we check that the reg64key is not null (shouldnt be null but you never know). Next we use the reg64key to open the key "SOFTWARE\Microsoft\ABCD". If this is not found (baseKey == null) then we create the key.
Finally you can set the key as you wish.
Hope this help.s

C# Registry SetValue throws UnauthorizedAccessException

Before you try to answer this with, "Do a quick Google search." I'd like to point out that I have already. Here is the situation, I have the following method that attempts to modify a registry key value. The problem I'm getting is that when executed, it throws an UnauthorizedAccessException even though I've opened the key as writeable. I'm running Visual Studio as administrator and even tried to make a small .exe with a manifest file forcing it to run as admin that will execute the code with no luck. The key already exists, it doesn't try to go into the CreateKey method. Here is the block of code.
Path = "S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System"
Key = "DisableTaskMgr"
NewValue = 1
public OperationResult ModifyKey()
{
OperationResult result = new OperationResult();
if (!Path.IsNullOrEmptyTrim())
{
if (!Key.IsNullOrEmptyTrim())
{
try
{
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
if (key != null)
{
key.SetValue(Key, NewValue);
key.Close();
}
else
{
result = CreateKey();
}
}
catch (Exception ex)
{
result.SetFail("Error accessing registry", ex);
}
}
else
{
result.SetFail("Registry key was null");
}
}
else
{
result.SetFail("Registry path was null");
}
return result;
}
Do I have to manually walk down the registry tree setting each OpenSubKey call to writeable? I tried this as well, still threw the same error...
in the var for your key
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, true);
change to
var key = Microsoft.Win32.Registry.Users.OpenSubKey(Path, RegistryKeyPermissionCheck.ReadWriteSubTree);
Have you tried setting the accessrule and permissions?
string user = Environment.UserDomainName + "\\" + Environment.UserName;
RegistryAccessRule rule = new RegistryAccessRule(user,
RegistryRights.FullControl,
AccessControlType.Allow);
RegistrySecurity security = new RegistrySecurity();
security.AddAccessRule(rule);
var key = Microsoft.Win32.Registry.Users.OpenSubKey(subKeyPath, RegistryKeyPermissionCheck.ReadWriteSubTree, RegistryRights.FullControl);
key.SetAccessControl(security);
One possible issue that I see with your code is that the Path variable is being set to a string that doesn't escape the \ characters. How about something like:
Path = #"S-1-5-21-1644491937-1078145449-682003330-5490\Software\Microsoft\Windows\CurrentVersion\Policies\System";
As a last ditch effort to figure out what was going on, I created a simple service to test this code that will run as the local system account. It's the highest privileges I could think of to try and run the code with. Running the code with these permissions worked.
Special thanks go out to 0_____0 and Charleh for pointing out the anti-virus as well. I checked the logs and it turns out it was trying to quarantine my changes. I guess even it won't stop the System user from making these changes though.
Special thanks go out to Sorceri as well for helping me research this so much.
In conclusion, if you're having intermittent, extremely odd behavior, check your virus scanner and permissions.
I ran into the same problem recently. So I tried a few things and instead of calling key.SetValue(Key, NewValue) simply calling create function solved my problem. That is;
Microsoft.Win32.RegistryKey key1 = Microsoft.Win32.Registry.Users.CreateSubKey(Path);
key1.SetValue(Key, NewValue);
CreateSubKey call doesn't delete the current entry but provided with the ability to write without exception. I hope that helps.
Only set grants to dword. You must to open Registry and at the last folder path, rigth click over it and set Grants, and select All Aplications and check Total Control. I hope to help you.
just Registry.SetValue(sub_key, key, value);
Example:
Registry.SetValue(
#"HKEY_CURRENT_USER\Software\Microsoft\Windows\CurrentVersion\Run",
"MyApp",
Application.ExecutablePath);

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