Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Replace Text in a TextFile c#

Tags:

c#

.net

What is the best way to replace text in a text file?

  1. I do not want to give the file a new name
  2. I do not want the text to become one long string which is what happens when I use File.ReadAllText because this is stored as a string and I loose carriage returns etc...

Also, I guess I will run into issues using a StreamReader/StreamWriter because you cannot read and write to the same file?

Thanks

like image 319
realtek Avatar asked Apr 17 '26 08:04

realtek


1 Answers

You can do it with a stream opened for both reading and writing:

FileStream fileStream = new FileStream(@"c:\myFile.txt", FileMode.OpenOrCreate, FileAccess.ReadWrite, FileShare.None);
var streamWriter = new StreamWriter(fileStream);
var streamReader = new StreamReader(fileStream);

...

fileStream .Close();

But the most easy way is still to read all file, edit the text and write it back to the file:

var text = File.ReadAllText(@"c:\myFile.txt");

...

File.WriteAllText(@"c:\myFile.tx", text);
like image 63
Ludovic Feltz Avatar answered Apr 18 '26 22:04

Ludovic Feltz



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!