How would I delete data from a text file once I find a specific string

shurb

Member
Joined
Oct 9, 2007
Messages
16
Programming Experience
1-3
So I have a text file and it contains useless info, (to me at least :) ), after a certain point. How could I delete the remainder of the file contents from a file at a point when a specific line is found?

For example I have a file called checkme.txt

Lines 1-25 contain the info I need to extract
Line 26 contains a line that reads, "Useless info from here down"
Lines 27 and beyond need to be deleted and the file saved as checkme.txt but with the data deleted.


Seems simple but for some reason I cannot accomplish it :(
 
Start with these help topics: File Access with Visual Basic
There is no such concepts as "deleting part of file", you have to read the old content and write the new content. Several of the options listed can be used, but if the content is large using stream based readers/writers may be better than filling the whole content into memory before processing it.
 
John.. I recall in java that some of the file accessor classes allowed the .Length property to be set as well as got. Issuing a set for a length shorter than the current file length caused the file to be quickly truncated by update to the file access tables, rather than reading and writing the content

Do you know if any of the streams or other file access classes (fileinfo?) can truncate a file in this manner? I seem to recall reading it somewhere but cannot find it
 
Read-write streams can truncate at a byte position with SetLength method, it is mostly suitable for files with binary content aligned for this purpose. While it is possible to truncate a text file at a given byte position it can be difficult to calculate where this should be. For example with a Utf8 encoded text file each char may occupy between 1-4 bytes and there may be 1-2 linefeed chars and the file may or may not have a preamble. Opening a FileStream and a StreamReader you can no longer read the stream position.
 

Latest posts

Back
Top