Manipulating text files...

  • Thread starter Thread starter genc_ ymeri at hotmail dot com
  • Start date Start date
G

genc_ ymeri at hotmail dot com

Hi,
I have some text files and all I need is to look for a certain word a
replace it with another one. What is the best way of doing this ?

Thank You very much for any tip,
G.Y.

PS:
I'm trying not to rewrite the entire file but as soon as I get the wanted
word just replace that word and quit from that process...
 
I wouldn't recommend this, as the Regex class works with strings, not
streams. If the size of the files are large, then you would have to load
the complete contents of the file into a string, and that could kill
performance.

Rather, you should just scan through the bytes and search for the word
yourself. Once you find the first character/byte that matches, you would
determine if that is the word, and then replace it.

When replacing, you are going to have to create a new file, or re-write
the bytes to the original file while scanning through them.

Hope this helps.
 
hi,

This is a pseudo code but will give you a good idea

//open the file
StreamReader reader = new StreamReader( ..... );
//open a temporary file ( use Path.GetTempPath/GetTempFileName for this file
StreamWriter writer = ....
//read a line at a time
string line;
while( (line= stream.ReadLine() ) != null )
//look for the word
if ( line.LastIndexOf( word) != -1 )
writer.WriteLine( line.Replace( word, newword) );

//close streams
reader.Close();
writer.Close();

//overwrite source file
File.Delete( .. .);
File.Copy( tempfile, origfile );



cheers,
 
Back
Top