Replace text in TextFile c #

What's the best way to replace text in a text file?

  • I don't want to give the file a new name
  • I don't want the text to become one long line, which is what happens when I use File.ReadAllText, because this is stored as a string and I lose carriage returns, etc.

Also, I think I am going to have problems using StreamReader / StreamWriter because you cannot read and write to the same file?

thank

+3


source to share


2 answers


You can do this with a stream open for 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 easiest way is to read the whole file, edit the text, and write it to the file:

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

...

File.WriteAllText(@"c:\myFile.tx", text);

      

+7


source


Depending on your file format, you can also read your files line by line (using File.ReadLines) and perform text replacements on each line.

You can also refer to this answer for a stream based option, which is the preferred way if your file is large.



How can I read a large (1GB) txt file in .NET?

0


source







All Articles