Search code examples
c#io

How do i properly update information in a text file?


I want to save some data in a text file like this:

Name = Frank
Age = 28
Registered = False

Now i want to read/update the Data contained in each row. For example I need to change the Name to "Tim", I have to find row Name and than replace the string after the "="

Im not quiet sure how to solve this properly and i couldnt find anything on Google that satisfied me

I tried to update it with the text.Replace() method but it only chances the string it actually finds.

I expect to read the correct data out of the row and replace it if needed


Solution

  • There are a wide variety of ways to do this. I'll contribute one of them (which I think is simpler to understand).

    Step 1: Read the entire file into a string.

    Step 2: Convert it to string.

    Step 3: Process the string using simple methods like split and join.

    Step 4: Overwrite the previous file with the processed string.

    The code is below:

    if (File.Exists(your_file_path)){
        string yourfile = File.ReadAllText(your_file_path);
    
        // Now the file is a simple string that you can manipulate using
        // string split functions.
        // For Example:
    
        // break by lines
        string[] lines = yourfile.Split('\n');
        foreach (string line in lines){
            if (line.Substring(0,4) == "Name"){
                // replace the necessary line
                line = "Name = Tim";
                break;
            }
        }
    
        // Join the array again
        yourfile = lines.Join("\n", lines);
        File.WriteAllText(your_file_path, yourfile);
    }