控制台应用无法读取非空文本文件问题排查与解决
程序数据库读取异常问题排查记录
问题背景
我开发了一款支持加载数据库文件、添加物品的程序,此前存在关闭应用时数据库文件无法保存的问题。添加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
相关产品推荐
相关产品推荐

