realtek
realtek

Reputation: 841

Replace Text in a TextFile c#

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

Upvotes: 3

Views: 201

Answers (2)

Julien Jacobs
Julien Jacobs

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

Ludovic Feltz
Ludovic Feltz

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

Related Questions