Jared
Jared

Reputation: 406

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. :)

Upvotes: 0

Views: 421

Answers (2)

Shadow Wizard
Shadow Wizard

Reputation: 66389

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);

Upvotes: 1

user1231231412
user1231231412

Reputation: 1659

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

Upvotes: 1

Related Questions