yosafat yosafat - 24 days ago 7x
C# Question

C# how to append text in end of row text file?

i have text file like this

IPen ID,Datetime,Status,Data Received

is it possible to add some
in end of row. I want append some
so the final result is :

IPen ID,Datetime,Status,Data Received,Data Reply

i already browsing and searching, the result only show append text in new line, but thats not what i want, i want append text in end of row. any suggestion for me?


You can add text at the end of an existing file like this:

        using (var stream = new StreamWriter("Your file path here"))
            stream.Write("Your text here");

This method will add the text in a new line only if there is already a end of line character on the end of file. Otherwise, it will add on the same line.

This also adds the text only on the end of the file, if you need to select the line or insert into all lines that match a specific condition it will be a little more complicated, but I can show you if you tell me exactly what you need.

EDIT: Since you need to add the text in the middle of a line, we should read all the lines, change then and save them back on the file:

        // Define your file path.
        var filePath = "Your file path here";

        // Fill an array with the lines from the txt file.
        var txtLines = File.ReadAllLines(filePath);

        // Change all lines into what you want.
        var changedLines = ChangeLines(txtLines);

        // Write the file with all the changed lines.
        File.WriteAllLines(filePath, changedLines);

And this is how to change the lines:

    public static IEnumerable<string> ChangeLines(IEnumerable<string> lines)
        foreach (var line in lines)
            yield return line.Replace("A C", "A B C");

This will replace all the occurrences of "A C" with "A B C". If you want to add something after some text, before, split a line in two or whatever you want, you can change this method to do what you want and all the changes will be saved back into the file. I hope that helps.