I am working on my uni project on C#. It requires me to create a student management system in C# console. I have to use text file for saving data. I can add data and retrieve data in text file but unable to update any student record. My question is how I can update specific student record in text file? For example my program will ask user to input student that he wants to update than program should fetch the complete the record of that student. The program again ask user to select the field or fields that he wants to update. After updating the field the record should be updated.
This code is not doing the job for me.
StringBuilder newFile = new StringBuilder();
string temp = null;
string userchoice = null;
string replacetext =null;
string update = null;
Console.WriteLine("enter the id of student to update the record");
userchoice = Console.ReadLine();
String[] file=File.ReadAllLines(@"myfile.txt");
foreach (string line in file)
{
if(line.Contains(userchoice))
{
Console.WriteLine("enter the data you want to replace");
replacetext=Console.ReadLine();
if(line.Contains(update)){
Console.WriteLine("enter the data you want to replace with");
update=Console.ReadLine();
temp=line.Replace(replacetext,update);
newFile.Append(temp+"\r\n");
continue;
}
newFile.Append(line+"\r\n");
}
File.WriteAllText(@"myfile.txt",newFile.ToString());