首页 > 解决方案 > 向 Main (string [] args) 提供输入时出错

问题描述

我有一个程序将通过“打开方式...”菜单运行,并将路径文件作为程序的输入。我的代码如下:

 static void Main(string[] args)
    {
        Application.EnableVisualStyles();
        Application.SetCompatibleTextRenderingDefault(false);
        if (args[0] != null)
        {
            Application.Run(new Form1(args[0]));
        }
        else
        {
            Application.Run(new Form1(""));
        }
    }

当给输入程序时它会正确运行,但是当我在没有输入的情况下输入程序时,通常会出现以下错误:

System.IndexOutOfRangeException: 'Index was outside the bounds of the array.'

有没有办法解决这个问题?

标签: c#winforms

解决方案


检查args不为空:

if(args.Any()) 
{
  // use args[0] here
  ....
}
else
{
  ....
}

您遇到的错误意味着它args是空的,因此访问第一个元素(在 0 索引处)是非法的。


推荐阅读