Avoid exception when check components in IIS if not installed

Binumon George 161 Reputation points
2022-09-01T14:24:20.417+00:00

Hi All,
I am checking in my computer installed IIS, Windows Authentication, Forms Authentication, Asp.Net in IIS. through .net application. Below giving my code

`RegistryKey registryKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry64).OpenSubKey(@"Software\Microsoft\InetStp\Components");

 isWindowAuthenticationInstalled(registryKey )  

 private bool isWindowAuthenticationInstalled(RegistryKey registryKey)  
    {  
        string sRegistryValue = registryKey.GetValue(@"WindowsAuthentication").ToString();  
        if (sRegistryValue == "1")  
            return true;  
        else  
            return false;  
    }`  

This code working as expected. But if windows authentication not installed i am getting exception.
How we avoid that. Sametime I want to get other components like Forms Authentication,Asp.net if they installed

Internet Information Services
0 comments No comments
{count} votes

1 answer

Sort by: Most helpful
  1. Michael Taylor 48,826 Reputation points
    2022-09-01T17:03:58.593+00:00

    Please use the Code Sample button to insert formatted code into your post. The code you posted isn't valid C# code and is hard to read as well.

    Just a quick guess but GetValue("WindowsAuthentication") would return null if there was no value. Hence you're dereferencing a null object and it crashes. To just fix this line of code you'd do something like this:

       private bool isWindowAuthenticationInstalled ( RegistryKey registryKey )   
       {  
          var value = registryKey.GetValue("WindowsAuthentication")?.ToString() ?? "0";  
         
          return Int32.TryParse(value, out var result) ? result : false;  
       }