You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

C#读取驾照考试答案文件到ListBox时触发空参数异常,求解决

解决System.ArgumentNullException: Value cannot be null. Parameter name: item异常

问题分析

你的代码触发异常有两个核心原因:

  1. 仅读取一行文件内容:代码中没有循环读取逻辑,只执行了一次inputFile.ReadLine(),导致Answers数组仅第一个元素有值,其余19个元素都是null。往listBox1添加null元素时就会抛出ArgumentNullException。
  2. 循环边界错误:for循环条件i <= Answers.Length会让循环执行21次(i从0到20),但数组有效索引范围是0-19,i=20时会触发索引越界,同时也会尝试添加更多无效的null值。

修复后的代码

namespace DriversLicenceExam
{
    public partial class Form1 : Form
    {
        public Form1()
        {
            InitializeComponent();
        }
        private void button1_Click(object sender, EventArgs e)
        {
            LoadKey();
            LoadAnswer();
        }
        private void LoadKey()
        {
            try
            {
                const int AnsLgth = 20;
                string[] Answers = new string[AnsLgth];
                int index = 0;

                // 使用using自动管理文件资源,无需手动Close
                using (System.IO.StreamReader inputFile = File.OpenText("DRIVERKEY.txt"))
                {
                    // 循环读取直到文件末尾,且不超过数组长度
                    while (index < AnsLgth && !inputFile.EndOfStream)
                    {
                        Answers[index] = inputFile.ReadLine()?.Trim(); // Trim去除换行符和空格
                        index++;
                    }
                }

                // 遍历数组有效索引(0到19)
                for (int i = 0; i < Answers.Length; i++)
                {
                    string value = Answers[i];
                    // 额外判断,避免添加null(如果文件行数不足20的情况)
                    if (!string.IsNullOrEmpty(value))
                    {
                        listBox1.Items.Add(value);
                    }
                }
            }
            catch (Exception ex)
            {
                // 可添加错误提示,比如MessageBox.Show(ex.Message);
                throw;
            }
        }
    }
}

关键修改说明

  • 循环读取文件:添加while循环,持续读取文件内容直到数组填满或文件结束,保证Answers数组尽可能被有效值填充。
  • 修正循环边界:将i <= Answers.Length改为i < Answers.Length,只遍历数组的有效索引范围。
  • 资源自动管理:使用using语句包裹StreamReader,确保文件资源自动释放,避免手动调用Close()可能引发的问题。
  • 空值防护:添加string.IsNullOrEmpty(value)判断,即使文件行数不足20,也不会往列表添加null或空字符串。

内容的提问来源于stack exchange,提问作者Tripnmarshall

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.14 07:30:50