NullReferenceException when Invoking Method to Enable/Disable Smart Card Reader using C#

28 views Asked by At

I am working on a C# application to enable and disable a smart card reader programmatically. I've implemented a method to retrieve the smart card reader device using WMI (Windows Management Instrumentation) and then invoke the "Enable" or "Disable" method based on the provided boolean parameter.

However,its working its enable disable the smart card reder but during runtime, I encounter a NullReferenceException at the line where I attempt to invoke the method. Here's the relevant portion of my code:

try
{
    device.InvokeMethod(enable ? "Enable" : "Disable", null);
    Console.WriteLine($"Smart card reader {(enable ? "enabled" : "disabled")}.");
}
catch (Exception ex)
{
    Console.WriteLine($"Error invoking method: {ex.Message}");
}

here is the full code :

using System;
using System.Management;

namespace deviceManager
{
    public class SmartCardReaderManager
    {
        public static ManagementObject GetSmartCardReader()
        {
            var query = new ManagementObjectSearcher("SELECT * FROM Win32_PnPEntity WHERE ClassGuid = '{50DD5230-BA8A-11D1-BF5D-0000F805F530}'");

            foreach (ManagementObject device in query.Get())
            {
                return device;
            }
            return null;
        }

        public static void DisableEnableSmartCardReader(bool enable)
        {
            var device = GetSmartCardReader();
            if (device != null)
            {
                try
                {
                    device.InvokeMethod(enable ? "Enable" : "Disable", null);
                    Console.WriteLine($"Smart card reader {(enable ? "enabled" : "disabled")}.");
                }
                catch (Exception ex)
                {
                    Console.WriteLine($"Error invoking method: {ex.Message}");
                }
            }
            else
            {
                Console.WriteLine("Smart card reader not found.");
            }
        }

        public static void Main(string[] args)
        {
            try
            {
                // Example usage: disable and then enable the smart card reader
                DisableEnableSmartCardReader(true);
            }
            catch (Exception ex)
            {
                Console.WriteLine($"Unhandled exception occurred: {ex.Message}");
            }

            Console.ReadKey();
        }
    }
}


I am working on a C# application to enable and disable a smart card reader programmatically. I've implemented a method to retrieve the smart card reader device using WMI (Windows Management Instrumentation) and then invoke the "Enable" or "Disable" method based on the provided boolean parameter.

However,its working its enable disable the smart card reder but  during runtime, I encounter a `NullReferenceException` at the line where I attempt to invoke the method
0

There are 0 answers