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

如何通过控制台程序向已有库存文本文件添加新条目?

库存管理程序添加新条目问题

我有一个库存管理程序,已有库存条目存储在文本文件中,用户可增加各条目的库存数量。现需添加代码,支持用户通过命令行输入添加文本文件中原本不存在的全新库存条目。

现有加载代码

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);
    }
}

文本文件格式示例

6
apple tools,111,temp desc,6
pear tools,222,temp desc,5
mango,333,temp desc,6
orange,444,temp desc,7
strawberry,555,temp desc,1
peach,666,temp desc,2

我尝试用StreamWriter和AppendText添加新行,但由于文件开头有固定的条目总数,是否需要重写全部代码?


解决方案

必须重写整个文件,因为文件开头的总数是当前条目数,直接追加新行只会增加条目但不更新总数,后续调用LoadDb时会因为总数与实际条目数不匹配导致加载错误。

具体实现步骤

  1. 加载现有库存到内存:通过LoadDb方法把所有条目加载到inventories数组中。
  2. 接收用户输入新条目:获取名称、编码、描述、库存数,创建新的Inventory对象。
  3. 扩展内存中的库存集合:由于C#数组是固定长度,需要扩容数组并添加新条目;更推荐改用List<Inventory>存储,避免手动扩容的麻烦。
  4. 重写整个文件:先写入更新后的条目总数,再逐个写入所有库存条目。

示例代码

1. 新增保存方法SaveDb

public void SaveDb(string fname)
{
    try
    {
        // 使用using自动释放文件资源
        using (StreamWriter sw = new StreamWriter(fname))
        {
            // 写入更新后的条目总数
            sw.WriteLine(inventories.Length);
            // 逐个写入条目
            foreach (var inventory in inventories)
            {
                sw.WriteLine($"{inventory.Name},{inventory.Code},{inventory.Description},{inventory.Stock}");
            }
        }
        Console.WriteLine("库存已成功保存");
    }
    catch (Exception exc)
    {
        Console.WriteLine($"保存失败: {exc.Message}");
    }
}

2. 添加新条目的逻辑

// 接收用户输入
Console.WriteLine("请输入新库存名称:");
string newName = Console.ReadLine();
Console.WriteLine("请输入编码:");
int newCode = int.Parse(Console.ReadLine()); // 建议添加输入验证,避免非数字输入报错
Console.WriteLine("请输入描述:");
string newDesc = Console.ReadLine();
Console.WriteLine("请输入库存数量:");
int newStock = int.Parse(Console.ReadLine());

// 创建新条目
Inventory newInventory = new Inventory(newName, newCode, newDesc, newStock);

// 扩容数组并添加新条目
Array.Resize(ref inventories, inventories.Length + 1);
inventories[inventories.Length - 1] = newInventory;

// 保存到文件
SaveDb("inventory.txt");

优化建议

  • 把inventories的类型从数组改为List<Inventory>,这样添加条目时直接调用Add方法,无需手动扩容数组,代码更简洁高效:
    // 修改LoadDb中的初始化
    inventories = new List<Inventory>();
    // 循环内添加元素
    inventories.Add(new Inventory(name, code, description, stock));
    // 添加新条目时
    inventories.Add(newInventory);
    // SaveDb中写入总数改为sw.WriteLine(inventories.Count);
    
  • 对用户输入进行验证(比如编码和库存数必须是数字),避免程序崩溃。

内容的提问来源于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 12:43:21