Click to See Complete Forum and Search --> : remove the last line from StreamReader
imin
August 20th, 2007, 10:48 PM
hi...
how do we remove the last line of the file we open in StreamReader? and then we saved the edited file (without the last line). is there any way to do it?
any help is greatly appreciated. thanks a lot
Mutant_Fruit
August 20th, 2007, 11:27 PM
There's the smart way:
Open the file using a FileStream, seek to the end of the file, then start scanning backwards byte by byte until you come across a newline character (meaning you have a /n with a /r before it). Then you just set the length of the file equal to the current position which should truncate the file so the last line is gone.
Then there's the easy way:
Open the file using a file stream. Read it in line by line and write out each line into a new file. You put in logic so that you don't copy the last line into the new file. Then just close both filestreams and delete the original file and rename the new file to the same name as the old flie.
Homogenn
August 21st, 2007, 02:06 AM
There's the smart way:
Open the file using a FileStream, seek to the end of the file, then start scanning backwards byte by byte until you come across a newline character (meaning you have a /n with a /r before it). Then you just set the length of the file equal to the current position which should truncate the file so the last line is gone.
Then there's the easy way:
Open the file using a file stream. Read it in line by line and write out each line into a new file. You put in logic so that you don't copy the last line into the new file. Then just close both filestreams and delete the original file and rename the new file to the same name as the old flie.
I'd agree to this, although I'd probably use the easy way with the exception that I'd load the entire file into a string, close the file, shorten the string accordingly, and then overwrite the old file with the new string.
Mutant_Fruit
August 21st, 2007, 07:33 AM
I'd agree to this, although I'd probably use the easy way with the exception that I'd load the entire file into a string, close the file, shorten the string accordingly, and then overwrite the old file with the new string.
I just hope it's not a large file then.
*tries to imagine loading a 500 megabyte string in memory* ;)
Homogenn
August 21st, 2007, 08:53 AM
I just hope it's not a large file then.
*tries to imagine loading a 500 megabyte string in memory* ;)
Haha, yeah, okay, if it's a big file, I'd probably do it the smart way, anyway :p
imin
August 23rd, 2007, 07:50 PM
thanks a lot for the help... i've done it using the easy way you proposed.. thanks again :D
but now i've another problem.. i will open a new thread about it... hope you all can help again :D
codeguru.com
Copyright Internet.com Inc., All Rights Reserved.