Aburley
Aburley

Reputation: 63

Replace one line in a text file

I have a text file that is used by another application as a configuration file. I have read in each line of the file into a String array:

string[] arrLine = File.ReadAllLines(pathToFile);

which works exactly how i need it to.

Now, all i need to do is replace the entire line of arrLine[x] with a string, overwriting what is there on that line and that line only. I have wrote code to know the exact line i need to replace, i just need to know how to replace it.

I am thinking of arrLine[x].Replace(oldString, newString) - if this works, how would i actually commit the change to the text file? Do i somehow need to rewrite the whole file? Im thinking that would be a little on the inefficient side when only one line needs rewriting?

Upvotes: 6

Views: 14248

Answers (1)

Reed Copsey
Reed Copsey

Reputation: 564801

You should be able to just assign that element:

arrLine[yourLineNumber] = "Foo";

how would i actually commit the change to the text file?

Once you've done this, you can use File.WriteAllLines(pathToFile, arrLine); to write the data back to the original file.

Upvotes: 7

Related Questions