Answered by:
read a file and write in the same file

Question
-
Hello,
The application should read a file and make some changes in the same file. The changes should be saved at the end of the operation.
I can read a file and find the line which should be updated. However I need help to how to do the rest of the work.
How can I update this line? Should the line be deleted first or is it possible to update the line while reading the file? Which functions should be used?
Thanks in advance,
Sedso
SedsoTuesday, August 16, 2011 2:27 PM
Answers
-
Open destination file
for each line in source file
if source line should be replaced then write replacement line in destination file
else write line in destination file
"The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination." - Fred Brooks- Marked as answer by sedso Thursday, August 18, 2011 11:58 AM
Tuesday, August 16, 2011 2:36 PM
All replies
-
Generally you have to read the file and write to a new one with the changes.
It might be possible to read all the lines into an array, close the file, edit the array entries and then write them out.
It is possible t do in place changes but that is not so easy - usually only done if the file has fixed lengths 'records'.
Regards David R
---------------------------------------------------------------
Every program eventually becomes rococo, and then rubble. - Alan Perlis
The only valid measurement of code quality: WTFs/minute.Tuesday, August 16, 2011 2:33 PM -
Open destination file
for each line in source file
if source line should be replaced then write replacement line in destination file
else write line in destination file
"The programmer, like the poet, works only slightly removed from pure thought-stuff. He builds his castles in the air, from air, creating by exertion of the imagination." - Fred Brooks- Marked as answer by sedso Thursday, August 18, 2011 11:58 AM
Tuesday, August 16, 2011 2:36 PM -
You can do something like this
//read all content string[] allLines = File.ReadAllLines("c:\\samplefile.txt"); //Now I will make changes to 3rd line allLines[2] = "I changed this line"; //write content back to file File.WriteAllLines("c:\\samplefile.txt", allLines);
Hope this helps.
Please mark this post as answer if it solved your problem. Happy Programming!- Proposed as answer by Andreas Johansson Tuesday, August 16, 2011 2:54 PM
Tuesday, August 16, 2011 2:44 PM