Reputation: 841
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
Upvotes: 3
Views: 201
Reputation: 2629
Depending on your file format, you could also read your files line by line (using File.ReadLines) and perform the text replacements for each line.
You can also refer to this answer for a variant based on streams, which is the preferred way if your file is large.
How to read a large (1 GB) txt file in .NET?
Upvotes: 0
Reputation: 11916
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);
Upvotes: 7