What is the best way to replace text in a text file?
Also, I guess I will run into issues using a StreamReader/StreamWriter because you cannot read and write to the same file?
Thanks
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With