tags:

views:

88

answers:

3

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());
A: 

First, I would define a "student" object.

public class Student
{
    public int ID { get; set; }
    public String Name { get; set;}
    // etc etc
}

Second, I'd use List<Student> to keep track of all students in the system.

Third, I would use XML Serialization to persist to disk, for retrevial upon program load. After all, XML is just text.

Nate Bross
+1  A: 

I'd suggest handling updates in a textfile by reading the whole textfile into memory, do the changes as needed to the in-memory data. Then write it to a temporary filename, delete the original file and rename the temporary file to the real filename.
This way you guard somewhat against file corruption (if the app crashes in the middle of updating the file, the original will be ok) and you can use the same code for adding and updating the contents.

Btw, you can use the AppendLine method of StringBuilder so you don't have to add \r\n.

ho1
A: 

If your data has some sort of structure to it, I would probably read it into a DataTable, do my updating/adding/deleting in memory, then write out a new file when the program exits or the user asks to save.

You can easily do this with XML and DataSets, as well.

Duracell