I found this code to search for a registry key, it works fine if i set it to void and have it pop up a window using messagebox.show , and i see the key it found. but, if i change it to return a string, the compiler fails with “not all code paths return a value” if i try to set a string in the method called “reg_result” and return it, i am returning the value to a string variable that calls the method.
string reg_result2 = Search_For_Registry_Keys(Registry.Users, search);
private static string Search_For_Registry_Keys(RegistryKey rk, string search)
{
string reg_result = "";
if (rk.SubKeyCount > 0)
{
foreach (var temp in rk.GetSubKeyNames())
{
if (temp.ToLower().Contains(search.ToLower()))
{
reg_result = (String.Format(rk.Name + "\\" + temp));
MessageBox.Show(String.Format("Match Found In Registry Key {0} Present At Location {1}", temp, rk.Name + "\\" + temp));
return reg_result;
}
}
foreach (var temp in rk.GetSubKeyNames())
{
try
{
if (rk.OpenSubKey(temp).SubKeyCount > 0)
{
Search_For_Registry_Keys(rk.OpenSubKey(temp), search);
}
}
catch
{
}
}
}
}
I then tried the following by putting a 2nd return after the if statement and that got rid of the compiling error about “not all code paths return a value”, but that didn’t seem to help as then the method would never return when i stepped through it until it reached the end of it’s searching, so I’m little lost on how to fix this?? yes i am newbie. I would think i my first code would work and i only need one return for when i find the result i am looking for… 🙂
Your code should look like this (comments indicate changes):
Note what I’ve done: if no key is found at all, then you return
""(the value initially assigned toreg_result). Also, when you recurse on a subkey (in the secondforeachloop,) and you do find a result, that result is immediately returned.Whenever you have a method that promises to return a value, you have to ensure that all code paths through it either a) actually return a value, or b) throw an uncaught exception.