0

我目前正在开展一个涉及大量学生的学校项目,我必须按字母顺序插入一个新学生并进行一些其他计算。我很难得到它,所以它只添加了一次新学生。我有一个 if 语句,但它似乎无法正常工作。

`//this adds the new student
        StreamWriter changeFile = new StreamWriter("Students.txt", true);
        string newStudent = "(LIST (LIST 'Malachi 'Constant 'A ) '8128675309 'iwishihadjessesgirl@mail.usi.edu 4.0 )";
        // this is where I am getting stumped
        if (File.Exists(newStudent))
        {
            changeFile.Close();
        }
        else
        {
            changeFile.WriteLine(newStudent);
            changeFile.Close();
        }`

每当我像这样运行代码时,它只会在我每次调试程序时添加新学生。我怎样才能让它只加他一次?

4

3 回答 3

3

File.Exists确定给定路径上的文件是否存在(为了记录,在尝试读取/写入文件之前您仍然应该这样做)。您试图找出给定的文本行是否存在于给定的文件中。这是一项非常不同的任务。

您需要通读文件中的行并将它们与给定的文本进行比较。

if(!File.ReadLines(filepath).Contains(newStudent))
{
    //TODO: Append student to the file
}
于 2013-11-07T18:22:55.770 回答
1

File.Exists(string path) 返回一个布尔值,用于确定文件是否存在于指定路径。 http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx

string newStudent 不是文件路径,所以它总是返回 false。

我认为你想要的是这样的:(这是通过记忆,所以它可能不会按原样编译)

var file = File.Open("students.txt");
var fileContents = file.ReadToEnd();
if (!fileContents.Contains(newStudent))
{
  file.WriteLine(newStudent);
}
file.Close();
于 2013-11-07T18:23:53.147 回答
1

首先将现有文件数据读入String变量,然后检查给定的学生数据在接收的文件中是否可用。如果没有找到给定的学生数据,则将新的学生数据写入文件,否则,如果已经存在,则关闭打开的 steream .

String StudentInfo = System.IO.File.ReadAllText("Students.txt");
    StreamWriter changeFile = new StreamWriter("Students.txt", true);


            string newStudent = "(LIST (LIST 'Malachi 'Constant 'A ) '8128675309 'iwishihadjessesgirl@mail.usi.edu 4.0 )";
            // this is where I am getting stumped
            if (StudentInfo.Contains(newStudent))
            {
                changeFile.Close();
            }
            else
            {
                changeFile.WriteLine(newStudent);
                changeFile.Close();
            }
于 2013-11-07T18:31:20.700 回答