Pages

Wednesday, July 24, 2013

C# Code to read the registry entry to check the authentication mode of Sql Server

C# Code to read the registry entry to check the authentication mode of Sql Server

There are few scenarios where we need to programmitically check what mode of authentication is available for sql server installed on a system. This is particularly useful in windows applications.The developer should know the key where its available in the registry.It also depends the type of machine AMD, Intel etc can have registry in different locations. 

I am sharing a sample code to do read an registry entry and check the authentication mode for sql server.

using System;
using System.Collections.Generic;
using System.Text;
using System.Security;
using System.Security.AccessControl;
using Microsoft.Win32;


namespace ReadWriteRegistryEntry
{
    class Program
    {
        static void Main(string[] args)
        {
            //Code to Read the registry entry to check the authentication mode of Sql Server
            try
            {
                string keyName = @"SOFTWARE\Microsoft\Microsoft SQL Server\MSSQL10.SQLEXPRESS\MSSQLServer";
                RegistryKey baseKey = RegistryKey.OpenBaseKey(RegistryHive.LocalMachine, RegistryView.Registry32);
                RegistryKey subkey = baseKey.OpenSubKey(keyName);

                if (subkey == null)
                {
                    Console.WriteLine("No Key found");
                }
                else
                {
                    try
                    {
                        if (subkey.GetValue("LoginMode").ToString() == "2")
                        {
                            Console.WriteLine("Mixed Mode");
                        }
                        else if (subkey.GetValue("LoginMode").ToString() == "1")
                        {
                            Console.WriteLine("Windows Authentication");
                        }

                    }
                    catch (Exception ex)
                    {
                        Console.WriteLine(ex.Message);
                    }
                }

            }
            catch (Exception e)
            {
                Console.WriteLine(e.Message);
            }
            Console.Read();

        }

    }
}

No comments:

Post a Comment