首页 > 解决方案 > System.ArgumentNullException: '值不能为空。参数名称:connectionString'

问题描述

我不明白为什么我在我的程序类上收到此系统异常错误

启动设置.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 文件所示。我确实有现有的连接字符串。OnCreateFromConnectionString 方法。这个方法不是必须启动那个json模板吗?它看不到的是什么?请帮助我谢谢。

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

解决方案


一开始你可能没有参数。将其更改为“if(args.Length > 0)”在“if(string.IsNullOrEmpty(...)”语句中

编辑:对不起,我都换了

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

推荐阅读