Reputation: 1178
I have a Win Forms application that among other things, moves a PC to a new OU then writes a DWORD value to the registry to indicate whether the move succeeded or failed. It reboots the PC after the rest of the operations complete. Upon reboot the application re-launches itself and checks registry values for what was successful and what was not, and displays 'checks' or 'X's on the form.
I am wondering how I can test to see if the DWORD value exists, then read whether it is a '1' or not. I realize I can just make this easy on myself and just have the application write a string value, but I am trying to learn.
Using Visual Studio I receive a warning when I try to check if the DWORD value is null I get the following warning: The result of the expression is always true since a value of type int is never equal to null of type int
Ok, so an int value cannot be null, so how else could I test to see if it exists in the registry to avoid an exception? See my code below.
RegistryKey domainJoin = Registry.LocalMachine.OpenSubKey
(@"SOFTWARE\SHIELDING\5", RegistryKeyPermissionCheck.ReadWriteSubTree);
//If the domain join was attempted, check outcome...
if (domainJoin != null)
{
//Check if move to OU was successful
int ouMoveVal = (int)domainJoin.GetValue("movePC");
if (ouMoveVal != null) <-----HERE IS WHERE I GET THE WARNING
{
//If PC move to new OU was successful
//show 'check' mark
if (ouMoveVal == 1)
{
picChkOU.Visible = true;
}
//If PC move to new OU was NOT successful
//show 'X' mark
else
{
picXOU.Visible = true;
}
}
Upvotes: 1
Views: 1902
Reputation: 164
Another solution...
using Microsoft.Win32;
private static int ReadRegistryIntValue(string sSubKey, string sKeyName)
{
try
{
int retValue = 0;
RegistryKey rkSearchFor = Registry.LocalMachine.OpenSubKey(sSubKey);
if (rkSearchFor == null)
{
return retValue;
}
else
{
try
{
retValue = Convert.ToInt32(rkSearchFor.GetValue(sKeyName));
}
catch (Exception)
{
return 0;
}
finally
{
rkSearchFor.Close();
rkSearchFor.Dispose();
}
}
return retValue;
}
catch (Exception)
{
return 0;
}
}
Upvotes: 0
Reputation: 11840
Change the order of the check so the object
is checked for null before you cast it to an int
:
//Check if move to OU was successful
object ouMoveVal = domainJoin.GetValue("movePC");
if (ouMoveVal != null)
{
// try to convert to int here and continue...
This means you benefit from the information provided by a null
object returned, indicating the key does not exist.
Then you can Int32.TryParse
to see if it's an int
after the null
check.
Upvotes: 2
Reputation: 35270
You could do something like this using a nullable int
-- i.e. int?
-- and the GetValue
overload that takes a default value if the reg value doesn't exist:
int? ouMoveVal = (int?) domainJoin.GetValue("movePC", new int?());
if (ouMoveVal.HasValue)
More on nullable: https://msdn.microsoft.com/en-us/library/b3h38hb0%28v=vs.110%29.aspx?f=255&MSPPError=-2147217396
Upvotes: 3