Introduction

Azure IoT Hub is a cloud gateway which supports open source SDKs and multiple protocols. IoT Hub communicates both ways - devices to cloud and cloud to devices. The IoT Hub monitoring helps to check device health, failures, and device connection status.
Please read the previous parts of the series before continuing with this one.
  1. How To Create Azure IoT Hub Using PowerShell
  2. How to Register IoT Device in Azure IoT Hub Using PowerShell
  3. How To Send Telemetry From An IoT Device To The Azure IoT Hub Using C#
  4. How To Configure Message Routing With IoT Hub - Part One
  5. How To Configure Message Routing With IoT Hub - Part Two
  6. How To Setup Diagnostic Logs With An IoT Hub

Creating a C# Console Application

How To Bulk Import IoT Devices In Azure IoT Hub Using C#
How To Bulk Import IoT Devices In Azure IoT Hub Using C#

Installing Microsoft.Azure.Devices NuGet package

How To Bulk Import IoT Devices In Azure IoT Hub Using C#

Get IoT Hub Connection string from Azure IoT Hub

How To Bulk Import IoT Devices In Azure IoT Hub Using C#
Open the program.cs file and type the below code.
  1. using System;
  2. using System.Threading.Tasks;
  3. using Microsoft.Azure.Devices;
  4. using Microsoft.Azure.Devices.Common.Exceptions;
  5. namespace IoTDeviceBulkImpExp
  6. {
  7. class Program
  8. {
  9. private static RegistryManager registryManager;
  10. private static string connectionString = "Enter the IoT Hub Connection String";
  11. static async Task Main(string[] args)
  12. {
  13. registryManager = RegistryManager.CreateFromConnectionString(connectionString);
  14. string deviceId = "device";
  15. for (int i = 0; i < 10; i++)
  16. {
  17. string newDeviceId = deviceId + i;
  18. await AddDeviceAsync(newDeviceId);
  19. }
  20. }
  21. private async static Task AddDeviceAsync(string deviceId)
  22. {
  23. //string deviceId = "DeviceThree";
  24. Device device;
  25. try
  26. {
  27. Console.WriteLine("New device:");
  28. var d = new Device(deviceId);
  29. device = await registryManager.AddDeviceAsync(d);
  30. }
  31. catch (DeviceAlreadyExistsException)
  32. {
  33. Console.WriteLine("Already existing device:");
  34. device = await registryManager.
  35. GetDeviceAsync(deviceId);
  36. }
  37. Console.WriteLine("Generated device key: {0}",
  38. device.Authentication.SymmetricKey.PrimaryKey);
  39. }
  40. }
  41. }
Run the project using F5 function key.
How To Bulk Import IoT Devices In Azure IoT Hub Using C#
How To Bulk Import IoT Devices In Azure IoT Hub Using C#
That’s it. I hope you have learned how to bulk import the IoT devices in Azure IoT Hub programmatically using C#. Feel free to fill up the comment box below if you need any further assistance.