Replace text in text file

  • Thread starter Thread starter Guest
  • Start date Start date
G

Guest

Hi

I would like to replace a string to an another into a text file (not a XML)
Have someone a example that I can take a look

ti
Samuel
 
For the moment it works like this in my application

// Open a file for reading
StreamReader streamReader
streamReader = File.OpenText(fileName)
// Now, read the entire file into a strin
string contents = streamReader.ReadToEnd();
streamReader.Close()

// Write the modification into the same fil
StreamWriter streamWriter=File.CreateText(fileName);

streamWriter.Write(contents.Replace("String1", "String2"));
streamWriter.Close();
 
Samuel said:
For the moment it works like this in my application :

// Open a file for reading
StreamReader streamReader;
streamReader = File.OpenText(fileName);
// Now, read the entire file into a string
string contents = streamReader.ReadToEnd();
streamReader.Close();

// Write the modification into the same file
StreamWriter streamWriter=File.CreateText(fileName);

streamWriter.Write(contents.Replace("String1", "String2"));
streamWriter.Close();

And what don't you like about the way it works at the moment? It could
certainly be more memory efficient if the files are large and your
replacements can work on a line-by-line basis (read a line, do the
replacement, write the line, repeat) - but otherwise, that looks mostly
okay.

I'd suggest using the using (...) construct rather than calling Close
explicitly though, as otherwise your files won't get closed immediately
if you get an exception.
 
Back
Top