Replace string in file

  • Thread starter Thread starter shapper
  • Start date Start date
S

shapper

Hello,

I have a XLST file where I have the phrase "HERE".

Something like:

<xsl:text>HERE</xsl:text>

I want to replace "HERE" by "UPDATED" and save the file.

Is this possible?

Thanks,

Miguel
 
Of course you can. Open the file using a StreamReader, and read it into a
StringBuilder line by line, using the StreamReader.ReadLine method. When you
find the line you want to do your replacement in, use the String.Replace
method to replace the text you want. When you've finished, write the file
back with a StreamWriter.

http://msdn2.microsoft.com/en-us/library/system.io.streamreader.aspx
http://msdn2.microsoft.com/en-us/library/system.io.streamwriter.aspx

You can optimize the memory usage of the StringBuilder by initilizing its
Length property to the length of the file, plus or minus the difference in
the length of the text you want to replace. This way, the StringBuilder
doesn't have to reallocate any memory, and only uses a buffer the exact size
of the file you want to read from and write to.

http://msdn2.microsoft.com/en-us/library/system.text.stringbuilder.aspx

Of course, if the file is very large, you may want to read and write to a
file directly, rather than reading the whole contents into a StringBuilder,
but with an XSLT file, this is generally not the case.

--
HTH,

Kevin Spencer
Microsoft MVP
Short Order Coder
http://unclechutney.blogspot.com

The devil is in the yada yada yada
 
Back
Top