How to modify a specific line of a text (.txt) file with c# script in Unity?

I wanna modify a text (txt) file when I run a void function.
For example:

My txt file:
Hola
Hola
Hola

The function of my code:

void editFile(){

(Line 2 of the txt file) = “Hello”;

}

My txt file:
Hola
Hello
Hola

But how to write the code?

Please answer me the CODE instead of concept! As I really know the concept.
Tutorial videos are also welcome.

1 Like
using System;
using System.IO;

public class TxtModifier
{
    void ModifyTxt(string file)
    {              
        var lines = File.ReadAllLines(file);
        lines[1] = "Hello";
        File.WriteAllLines(file, lines);
    }

    //returns null if goes right, return error message if goes wrong
    string ModifyTxtWithNoSurprises(string file)
    {
        try
        {
            var lines = File.ReadAllLines(file);
            lines[1] = "Hello";
            File.WriteAllLines(file, lines);
        }
        catch(Exception e)
        {
            return e.Message;
        }
        return null;
    }
}

Anyway if your purpose is to save GameData google about PlayerPrefs

2 Likes

Thank you so much.

1 Like