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
Printable View
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
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.Quote:
Originally Posted by Mutant_Fruit
I just hope it's not a large file then.Quote:
Originally Posted by Homogenn
*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 :pQuote:
Originally Posted by Mutant_Fruit
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