On 2007-11-22 00:45:47 -0800, "Jon Skeet [C# MVP]" <sk***@pobox.comsaid:
On Nov 22, 8:42 am, "TonyJ" <johansson.anders...@telia.comwrote:
>I supposed to modify some text files. In the file(s) which consist of
different section. In one section you might have
Path = <Installation_path>. The program will then replace the text string
Installation_path with the path that was chosen in the installation
program. [...]
Well, you can change where a StreamReader is, although it can be
tricky in some cases. However, you can't just insert or delete data
into/from a file - in your case c:\Work\PK\Program\Test\ is longer
than <Installation_pathso while you could overwrite
<Installation_pathyou would then overwrite the following text as
well.
I suggest you read the whole file into memory, then write out the
changed version.
Agreed. Or alternatively, read the file in piece by piece, replacing
text and writing it out as you go along. Even changing it in memory is
going to have problems similar to changing it in the file (though of
course rearranging the data in memory to accomodate changes in the
length of replaced text is easier, it's still extra work somewhere).
Assuming the file has line breaks and that a token to be replaced never
spans two or more lines, then a single line would be a convenient unit
to read at a time. You could use StreamReader.ReadLine(), then
String.Replace() to replace tokens, then StreamWriter.WriteLine() to
write out the new file.
You could do all the same reading the whole file into memory (using
instead ReadToEnd()), but then you'd be limited in the size of the
file, and performance would degrade as the file gets larger compared to
a line-by-line approach.
Granted, it may well be that the intended text files are so small these
issues don't matter, but in this case it's practically no difference to
implement a line-by-line version compared to reading everything at once
(an loop and then deleting the original file and moving the final file
back to the original file name is pretty much the only added code), I'd
go ahead and do that.
YMMV. :)
Pete