Link to home
Create AccountLog in
Avatar of fwsteal
fwsteal

asked on

seek to end of file, delete line

I need help with seeking to the end of a file, deleting a line and saving the file. Below is my windows text file and my code so far.

Windows Text File

102,,agent_disconnect,2007-02-27 22:54:44,0xffffffff,0xffffffff,,,,000.184.00.131,000.184.00.131,,,,,,,,,,,,
102,,agent_disconnect,2007-02-27 22:54:44,0xffffffff,0xffffffff,,,,00.109.000.010,00.109.000.010,,,,,,,,,,,,
102,,agent_discon
------------------------
Code:

//Goal: read to end of file and delete the last line, then save the file as win.txt
Dim myFile As String
myFile = "c:\logfiles\winlog.txt"

Dim fs As New FileStream("myFile", FileMode.Open, FileAccess.ReadWrite, FileShare.ReadWrite)
fs.Seek(0, SeekOrigin.End)
'read back and remove the last line?
'now save as new file in c:\logfiles\temp\win.txt
fs.Close()
ASKER CERTIFIED SOLUTION
Avatar of tpwells
tpwells

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
See answer
SOLUTION
Avatar of Mike Tomlinson
Mike Tomlinson
Flag of United States of America image

Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
SOLUTION
Link to home
membership
Create a free account to see this answer
Signing up is free and takes 30 seconds. No credit card required.
Hey Fernando...instead of rewriting the whole file, try using SetLength() to truncate the existing stream you have:
http://msdn2.microsoft.com/en-us/library/system.io.filestream.setlength.aspx

    "If the given value is less than the current length of the stream, the stream is truncated."

I haven't tied it myself...but maybe:

    fs.SetLength(currentPosition)
    fs.Close()
Hi Idle_Mind;

You are correct of course but in this case fwsteal wanted to save it to a different file.

You have a great day. ;=)

Fernando
Hehe...good point Fernando!

My short term memory even amazes me sometimes...  =)