使用控制台应用程序向预先存在的文本文件添加新行?

问题描述 投票:0回答:0

我有一个程序,它在一个文本文件中存储了库存中预先存在的项目,用户可以增加每个项目的数量。我正在尝试添加代码,让用户可以通过命令行输入添加一个以前不在文本文件中的全新项目。

这是我加载文件并将每个变量转换为特定数据类型以确保文件加载的代码:

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

我试过 Console.Write();使用 StreamWriter 和 AppendText 可以添加更多行,但是因为我已经有了固定的项目长度(文本文件中的 6),我需要在这里重做我的整个代码吗?

c# console-application
© www.soinside.com 2019 - 2024. All rights reserved.