When using C # To operate the registry, if the registry key type is REG_DWORD, an overflow bug may occur. There is very little information on the Internet. Share it here.
C # You can use the setvalue method of the registrykey class to set the key value. For example:
Everything looks normal, but this registryvaluekind. DWORD is faulty.
REG_DWORD in the registry is an unsigned 32-bit value, while registryvaluekind. DWORD in C # Is a signed 32-bit value. This means that the representation range of registryvaluekind. DWORD is smaller than that of REG_DWORD. Therefore, if you directly input a large number, an exception is thrown, indicating that the type is incorrect.
So how can we solve this bug?
Readers may try to do this:
Openkey. setvalue ("noviewondrive", convert. toint32 ("ffffffff", 16), registryvaluekind. DWORD );
The purpose is to forcibly convert the parameter to a 32-bit signed number. This is not acceptable. An exception is also prompted because ffffffff is beyond the 32-digit representation range and cannot be converted.
Or do this:
Openkey. setvalue ("noviewondrive", convert. touint32 ("ffffffff", 16), registryvaluekind. DWORD );
The purpose is to forcibly convert a parameter to an unsigned 32-bit representation. Similarly, the setvalue method automatically converts the parameter to a signed 32-bit representation. Therefore, our conversion is futile, it will also be converted back, and after conversion back, it will prompt that it is out of range.
In fact, the method to solve this problem is very simple. You only need to put the conversion process in the unchecked statement. The conversion in the unchecked statement block will not be checked for overflow. If it overflows, it will be directly indicated by the complement code. For example:
Int32 tempint = 0; // pre-define a 32-bit signed number of digits // The conversion within the unchecked statement block without Overflow check unchecked {tempint = convert. toint32 ("ffffffff", 16); // forcibly converted to a signed 32-digit number} // at this time, the tempint is already a signed 32-digit number and can be directly written into the openkey of the Registry. setvalue ("noviewondrive", tempint, registryvaluekind. DWORD );
In this way, the registry can be successfully written.