Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace one line in a text file

Tags:

c#

file-io

c#-4.0

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?

like image 450
Aburley Avatar asked Oct 22 '12 15:10

Aburley


People also ask

How do you replace a line in a text file in bash?

The 'sed' command is used to replace any string in a file using a bash script. This command can be used in various ways to replace the content of a file in bash. The 'awk' command can also be used to replace the string in a file.


1 Answers

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.

like image 160
Reed Copsey Avatar answered Oct 26 '22 16:10

Reed Copsey