为file.txt添加值 [英] Add value to file.txt

查看:61
本文介绍了为file.txt添加值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

您好,我有这段代码,这在我的Student.txt中添加了一行,但是,每次我编译并运行该代码时,它都会再次执行.我可以添加什么代码,以使新记录仅添加一次?

Hi, I have this code, which adds a line into my Students.txt, however, everytime I compile and run the code, it does it again. What code can I add so that the new record is only added once?

string newLastName = "'Constant";
            string newRecord = "(LIST (LIST 'Constant 'Malachi 'D ) '1234567890 'mdconstant@mail.usi.edu 4.000000 )";
            string line;
            string lastName;
            bool insertionPointFound = false;

            for (int i = 0; i < lines.Count && !insertionPointFound; i++)
            {

                line = lines[i];
                if (line.StartsWith("(LIST (LIST "))
                {
                    values = line.Split(" ".ToCharArray());
                    lastName = values[2];
                    if (newLastName.CompareTo(lastName) < 0)
                    {
                        lines.Insert(i, newRecord);
                        insertionPointFound = true;
                    }

                }


            }
            if (!insertionPointFound)
            {

                lines.Add(newRecord);                          //This record is always added, making the file longer over time 
                                                                //if it is not deleted each time from the Students.txt file in 
            }                                                  //the bin folder.


            File.WriteAllLines("Students.txt", lines);

推荐答案

您的循环正在搜索一个比您的newLastName大的名称,当找到该名称时,它将添加新记录.因此,只要文件中具有大于''Constant的任何名称,它就会重复添加记录.您应该先搜索一个相等的名称,然后再跳过插入.
Your loop is searching for a name that is greater than your newLastName and when found it adds the new record. So as long as you have any name that is greater than ''Constant in your file it will repeatedly add the record. You should be searching for a name that is equal first and then skipping the insert.


这篇关于为file.txt添加值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆