System.ArgumentNullException:'值不能为null。参数名称:connectionString'

时间:2019-09-09 13:08:07

标签: c# azure-iot-hub azure-iot-sdk

我不了解为什么我的Program类出现此系统异常错误

launchSetting.json

{
  "profiles": {
    "TwinDeviceApp": {
      "commandName": "Project",
      "environmentVariables": {
        "IOTHUB_DEVICE-CONN_STRING": "HostName=eNtsaIOTHubs.azure-devices.net;DeviceId=eNtsaDeviceId;SharedAccessKey=****="
      }
    }
  }
}


Main class

using System;
using Microsoft.Azure.Devices.Shared;
using Microsoft.Azure.Devices.Client;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace TwinDeviceApplication
{
    class Program
    {

        private static string s_deviceConnectionString = Environment.GetEnvironmentVariable("IOTHUB_DEVICE-CONN_STRING");
        private static TransportType s_transportType = TransportType.Amqp;
        public static int Main(string[] args)
        {
            if(string.IsNullOrEmpty(s_deviceConnectionString) && args.Length > 0)
            {
                s_deviceConnectionString = args[0];
            }
            DeviceClient deviceClient = DeviceClient.CreateFromConnectionString(s_deviceConnectionString, s_transportType);

            if(deviceClient == null)
            {
                Console.WriteLine("Failed to create DeviceClient");
                return 1;
            }
            var sample = new TwinDeviceApp(deviceClient);
            sample.RunSampleAsync().GetAwaiter().GetResult();

            Console.WriteLine("Done.\n");
            return 0;
        }
    }
}

我的connectionString到底缺少什么?如json-template文件所示。我确实有connectionString。 OnCreateFromConnectionString方法。此方法是否必须启动该json-template?它看不到什么?请帮我谢谢。

1 个答案:

答案 0 :(得分:0)

开始时可能没有参数。对其进行更改,使“ if(args.Length> 0)”位于“ if(string.IsNullOrEmpty(...)”语句中

编辑:对不起,我两者都切换了

if(args.Length > 0)
{
    if(string.IsNullOrEmpty(s_deviceConnectionString))
    {
        s_deviceConnectionString = args[0];
    }
}