C# Streamwriter if语句不工作
我目前正在做一个涉及大量学生的学校项目,我必须按字母顺序插入一个新学生,并做一些其他计算。我很难得到它,所以它只添加一次新的学生。我有一个if语句,但它似乎工作不正常C# Streamwriter if语句不工作,c#,C#,我目前正在做一个涉及大量学生的学校项目,我必须按字母顺序插入一个新学生,并做一些其他计算。我很难得到它,所以它只添加一次新的学生。我有一个if语句,但它似乎工作不正常 `//this adds the new student StreamWriter changeFile = new StreamWriter("Students.txt", true); string newStudent = "(LIST (LIST 'Malachi 'Constant 'A
`//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();
}`
每当我像这样运行代码时,每次调试程序时,它都会添加新的学生。如何使其仅添加一次?
File.Exists
确定给定路径下的文件是否存在(对于记录,在尝试读取/写入文件之前,您仍应执行此操作)。您试图找出给定的文本行是否存在于给定的文件中。这是一个非常不同的任务
您需要通读文件中的行,并将它们与给定的文本进行比较
if(!File.ReadLines(filepath).Contains(newStudent))
{
//TODO: Append student to the file
}
File.Exists
确定给定路径下的文件是否存在(对于记录,在尝试读取/写入文件之前,您仍应执行此操作)。您试图找出给定的文本行是否存在于给定的文件中。这是一个非常不同的任务
您需要通读文件中的行,并将它们与给定的文本进行比较
if(!File.ReadLines(filepath).Contains(newStudent))
{
//TODO: Append student to the file
}
Exists(字符串路径)返回一个bool,该bool确定指定路径上是否存在文件。
字符串newStudent不是文件路径,因此它将始终返回false
我想你想要的是这样的:(这是通过内存实现的,所以它可能不会按原样编译)
Exists(字符串路径)返回一个bool,该bool确定指定路径上是否存在文件。
字符串newStudent不是文件路径,因此它将始终返回false
我想你想要的是这样的:(这是通过内存实现的,所以它可能不会按原样编译)
首先将现有文件数据读入
字符串
变量,然后检查所接收文件中是否存在给定的学生数据。如果未找到给定的学生数据,则将新的学生数据写入文件,否则,如果已存在,则关闭打开的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();
}
首先将现有文件数据读入
字符串
变量,然后检查所接收文件中是否存在给定的学生数据。如果未找到给定的学生数据,则将新的学生数据写入文件,否则,如果已存在,则关闭打开的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();
}
如果您需要我添加Students.txt文件,我需要一些帮助,它有10000多名学生。
file.Exists
确定指定的文件是否存在。我不明白你想通过这种方式实现什么,我也尝试过newStudent!=空值也不能正常工作当然,它从来都不是空值。我们知道这一点,因为您只是将其设置为常量(非空)字符串。这就是我遇到的难题,我不知道如何让它检查字符串是否已在文本文件中。如果您需要我添加Students.txt文件,我需要一些帮助,它有10000多名学生。File.Exists
确定指定的文件是否存在。我不明白你想通过这种方式实现什么,我也尝试过newStudent!=空值也不能正常工作当然,它从来都不是空值。我们知道这一点,因为您只是将它设置为一个常量(非空)字符串。这就是我遇到的难题,我不知道如何让它检查字符串是否已经在文本文件中