Edit certain lines of textfile - c#
I have a text file...
HELLO GOODBYE FAREWELL
.. and two string variables, requested and newname. I am trying to write a program, that removes 'requested' from the text file and adds 'newname'. However I do not know the concepts and the code to do so. The only concept I can think of is adding all lines to an array then removing 'requested' from the array and adding 'newname' ... but I don't know the code.
I apologies if this is a stupid question, I am new to c#. Help is much appreciated. :)
Your idea should work fine.
Here's a link on how to get the text file contents into a list collection. http://www.dotnetperls.com/readline
Then you can use List.Add("newname"); and List.Remove("requested");
No stupid questions btw, only stupid ppl to post complaints about it :D
As simple as:
string path = "file path here"; List<string> lines = File.ReadAllLines(path).ToList(); lines.RemoveAll(line => line.Equals(requested)); lines.Add(newname); File.WriteAllLines(path, lines);