Search code examples
c#azureiotazure-iot-hub

How do I check the status (enabled or disabled) of an IoT device in Azure IoT hub portal through C# code?


I am writing a c# code where I need to check if an IoT device is disabled from the Azure Hub. Please help me with the c# code snippet how can I check it in the code if the device is enabled and disabled. Currently I am testing with 10 devices. Please help.


Solution

  • I refer to this post(How to disable Enable connection to IoT Hub?), and I guess we can use below code to test it.

    Offical Doc:

    1. Device Class

    2. DeviceStatus Enum

    Related Post

    1. How to disable Enable connection to IoT Hub?

        Dictionary<string,int> dic = new Dictionary<string, int>();
        // key-value    deviceid--status
        dic.Add("deviceid1",-1);
        ...
        dic.Add("deviceid10", -1);
        // init RegistryManager 
        var registryManager = RegistryManager.CreateFromConnectionString(iotHubConnectionString);
        Device device = null;
        foreach (var item in dic)
        {
            device= registryManager.GetDeviceAsync(item.Key);
            if (device != null)
            {
                dic[item.Key] = device.Status.DeviceStatus;
            }
            if (dic[item.Key] == -1)
            {
                Console.WriteLine("deviceid=" + item.Key + "  ,  device not found");
            }
            else {
                Console.WriteLine("deviceid=" + item.Key + "  ,  status=" + (dic[item.Key] == 1 ? "Disabled" : "Enabled"));
            }
        }
    

    enter image description here