Question read part of a file and write to another file.

myoda

New member
Joined
Oct 9, 2014
Messages
2
Programming Experience
1-3
Hello,

I have a text file that has middle section that I need to get the data from, and rest of it is junk, so I was wondering if it is possible to use vb.net to read the file, just grab the section I need and either write it too another file or just delete all the junk I don't need.

Thanks,
Sam
 
Nevermind, I figured out what I was looking to do.
    Public Sub Main()
        '
        Dim fileName As String = "Filepath"
        Dim startMark As String = "StartLine"
        Dim stopMark As String = "StopLine"


        ' A backup first    
        Dim backup As String = fileName + ".bak"
        File.Copy(fileName, backup, True)


        ' Load lines from the source file in memory
        Dim lines() As String = File.ReadAllLines(backup)


        ' Now re-create the source file and start writing lines not inside a block
        Dim insideBlock As Boolean = False
        Using sw As StreamWriter = File.CreateText(fileName)
            For Each line As String In lines
                If line = startMark Then
                    ' Stop writing
                    insideBlock = True


                ElseIf line = stopMark Then
                    ' restart writing at the next line
                    insideBlock = False


                ElseIf insideBlock = True Then
                    ' Write the current line outside the block
                    sw.WriteLine(line)
                End If
            Next
        End Using
        '
        Dts.TaskResult = ScriptResults.Success
    End Sub
 
Last edited by a moderator:
Back
Top