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

控制台应用无法读取非空文本文件问题排查与解决

程序数据库读取异常问题排查记录

问题背景

我开发了一款支持加载数据库文件、添加物品的程序,此前存在关闭应用时数据库文件无法保存的问题。添加saveDb方法实现库存变更保存后,程序完全无法读取文本文件。即使回退代码、重建项目、移除所有saveDb相关代码,控制台应用仍只能读取空文件。

加载数据库的核心代码

public void LoadDb(string fname)
{
    try
    {
        Console.WriteLine("Loading File {0}", fname);

        StreamReader sr = new StreamReader(fname);
        int count = Convert.ToInt16(sr.ReadLine());
        inventories = new Inventory[count];

        for (int i = 0; i < count; i++)
        {
            string[] line = sr.ReadLine().Split(',');
            string name = line[0];
            int code = Convert.ToInt32(line[1]);
            string description = line[2];
            int stock = Convert.ToInt32(line[3]);

            inventories[i] = new Inventory(name, code, description, stock);
        }

        sr.Close();

        Console.WriteLine("{0} records loaded.", count);
    }
    catch (Exception exc)
    {
        Console.WriteLine("Could not open file: ", exc.Message);
    }
}

排查过程与最终原因

尝试了代码回滚、项目重建、移除saveDb相关代码等操作,均未解决读取异常。最终发现问题根源在于文本数据库文件本身存在数据错误:某条物品记录的代码字段缺失,导致Convert.ToInt32(line[1])执行时抛出异常,程序进入catch块后终止加载流程,表现为无法正常读取文件内容。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.07.27 06:08:33