Simple FileReader / FileWriter

24 Apr, 2009 VB.NET

Have you ever needed to search through a large recordset in a FLAT file and write out only records that match a certain criteria to another file. We had that instance where we needed to search through a 750 MEG Text file (yeah, too big to open in Notepad) and find only transactions that match a certain account number for one of our clients being audited. The answer was a simple VB.NET Console Application. You simply loop through each line and using a Substring Command you evaluate whether the account number is present, if it is you write the entire line to another file that was created by the program during the process. VB.NET Code is pasted below…


Imports System.IO

Module Module1

Sub Main()

' The File you are needing to evaluate
Dim filename As String = "C:\PTTR0203.TXT"

'The text you are evaluating against
Dim searchkey As String = "20572733"

'Just to count for curiosity sake
Dim i As Integer = 0

'Create the StreamReader
Dim sr As StreamReader = File.OpenText(filename)

' Let yourself know the process began
Console.WriteLine("File Scanning Begun")

Dim input As String

' Make INPUT equal to each line in a loop of the file
input = sr.ReadLine()

' Find the account number space in the string
Dim myaccount As String

' Create the file you are going to write to,
' in this case it will create the file with whatever the SearchKey (Account number) is plus.txt

Dim fs As New FileStream("C:\" & searchkey & ".TXT", FileMode.Create, FileAccess.Write)

' Create the Streamwriter
Dim sw As New StreamWriter(fs)

' Begin your loop
While Not input Is Nothing
myaccount = input.Substring(4, 8 )

' Evaluate whether it matches your search string
If myaccount = searchkey Then
Console.WriteLine(input)

' Write it to a file
sw.WriteLine(input)
i = i + 1
End If

End While

' Close the reader
sr.Close()

' Dispose of the writer
sw.Dispose()

' Tell yourself you are done and how many records you scanned

Console.WriteLine("Process Complete " & i & " files processed")

End Sub
End Module

Comments are closed.