0

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

Jared
  • 396
  • 4
  • 14
  • have you tried anything at all yet? your idea is not bad, but you should try implementing it before asking for someone to do it for you... – madd0 Dec 01 '11 at 14:21
  • I haven't tried anything because I don't know the code the fill my concepts.. :S – Jared Dec 01 '11 at 14:33

2 Answers2

1

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

user1231231412
  • 1,659
  • 2
  • 26
  • 42
  • 1
    On the other hand, there is something to be said for finding existing answers: http://stackoverflow.com/questions/2044365/adding-a-line-to-the-middle-of-a-file-with-net – N_A Dec 01 '11 at 14:25
1

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);
Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208