Delete Selected Lines from Text File

  • Thread starter Thread starter cdun2
  • Start date Start date
C

cdun2

Hello,
I have some code that reads each line of a text file, and if a line is
found where the length of the string in the line is > 384, it writes
the line to a text file.

The other step that I need to take is to delete the line from the
source file. The code is as follows;

-*****************************************
Public Sub Main()
'find the records where the string length is greater than 384
'write them out to a file
'delete them from the source file
Dim oFile As System.IO.File
Dim oRead As System.IO.StreamReader
Dim oWrite As System.IO.StreamWriter
Dim LineIn As String

oRead =
oFile.OpenText("C:\Learning\SettlementDataTest\SC15_Copies\SingleFile\CDNSC.CDNSC.SC00015.11062006")
oWrite =
oFile.CreateText("C:\Learning\SettlementDataTest\SC15_Copies\ErrantRecords\ErrantRecords.txt")
While oRead.Peek <> -1
LineIn = oRead.ReadLine()
If Len(LineIn) > 384 Then
oWrite.WriteLine(LineIn)
'what do I do here to delete the 'LineIn' from the
source file?

End If
End While

oRead.Close()
oWrite.Close()
oFile = Nothing
LineIn = Nothing
Dts.TaskResult = Dts.Results.Success
End Sub
-*************************************
What would I do to delete the 'LineIn' found in the condition? By the
way, I'm doing this in a Script Task of a Integration Services package.

Thank you for your help!

cdun2
 
You need to be writing a temporary file from the source file, missing out
the lines you want to delete. When you've finished, delete the original
file and rename the temporary file.
 
cdun2 said:
I have some code that reads each line of a text file, and if a line is
found where the length of the string in the line is > 384, it writes
the line to a text file.

The other step that I need to take is to delete the line from the
source file. The code is as follows;

You /cannot/ delete lines from a sequential disk file. How do you
expect VB go about shunting all the remaining lines backwards on the disk?

Create two output files, one for the filtered lines, one for the rest
and, at the end of processing overwrite the source file with the latter.

Dim oIn as New StreamReader( "in.txt" )
Dim oOut1 As New StreamWriter( "out1.txt" )
Dim oOut2 As New StreamWriter( "out2.txt" )

Dim sRecord As String _
= oIn.ReadLine()
Do While Not ( sRecord Is Nothing )
If sRecord.Length > 384 Then
oOut1.WriteLine( sRecord )
Else
oOut2.WriteLine( sRecord )
End If
sRecord = oIn.ReadLine()
Loop
oOut1.Close()
oOut2.Close()
oIn.Close()

File.Copy( "out2.txt", "in.txt", True )

HTH,
Phill W.
 
Back
Top