Streamwriter if语句不起作用

时间:2013-11-07 18:17:01

标签: c#

我目前正在开展一项涉及大量学生的学校项目,我必须按字母顺序插入新学生并进行其他一些计算。我很难得到它,所以它只会增加新学生一次。我有一个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();
        }`

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

3 个答案:

答案 0 :(得分:3)

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

您需要仔细阅读文件中的行并将其与给定文本进行比较。

if(!File.ReadLines(filepath).Contains(newStudent))
{
    //TODO: Append student to the file
}

答案 1 :(得分:1)

File.Exists(字符串路径)返回一个bool,用于确定指定路径中是​​否存在文件。 http://msdn.microsoft.com/en-us/library/system.io.file.exists(v=vs.110).aspx

字符串newStudent不是文件路径,因此它将始终返回false。

我认为你想要的是这样的:(这是由内存所以很可能不会按原样编译)

var file = File.Open("students.txt");
var fileContents = file.ReadToEnd();
if (!fileContents.Contains(newStudent))
{
  file.WriteLine(newStudent);
}
file.Close();

答案 2 :(得分:1)

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

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