What is the fastest way to write to a text file?

venablc

Member
Joined
Jul 18, 2006
Messages
18
Programming Experience
Beginner
I am converting and old vb6 program into VB.NET for various reasons and have hit a problem....

Part of the program involves writing alot of lines to a file (upto 500,000). The original program can get through 250,000 lines in just over 2 minutes, here is the source code used for this:

VB.NET:
Dim fname As String, rsnap As New ADODB.Recordset, FH As Integer
    Dim buff As String
 
If fname <> "" And Err <> 32755 Then
       FH = FreeFile
       Open fname For Output As #FH%
 
       rsnap.Open "select mobile, status, lastping, network from view_ping_batch where pID=" & pID & " order by status, mobile", CNN, adOpenForwardOnly, adLockReadOnly
       While Not rsnap.EOF
             buff$ = ""
             buff$ = RTrim(rsnap("Mobile")) & vbTab
             buff = buff$ & rsnap("Status") & vbTab
             buff$ = buff$ & Format$(rsnap("lastping"), "dd mmm yyyy ttttt") & vbTab
             buff$ = buff$ & RTrim(rsnap("Network"))
             Print #FH%, buff$
             rsnap.MoveNext
       Wend
       rsnap.Close

In VB .NET the equivalent to this which i am using looks like this:

VB.NET:
Dim fname As String, rSNAP As New ADODB.Recordset, pID As Long, fh As Integer
Dim buff As String
If fname <> "" And Err().Number <> 32755 Then
Dim fs As New FileStream(fname, FileMode.Create, FileAccess.Write)
Dim s As New StreamWriter(fs)
s.BaseStream.Seek(0, SeekOrigin.End)
rSNAP.Open("select mobile, status, lastping, network, rcode from view_ping_batch where pID=" & pID & " order by status, mobile", CNN, ADODB.CursorTypeEnum.adOpenForwardOnly, ADODB.LockTypeEnum.adLockReadOnly)
While Not rSNAP.EOF
buff$ = ""
buff$ = RTrim(rSNAP("Mobile").Value) & vbTab
buff = buff$ & rSNAP("Status").Value & vbTab
buff$ = buff$ & Format$(rSNAP("lastping").Value, "dd mmm yyyy ttttt") & vbTab
buff$ = buff$ & RTrim(rSNAP("Network").Value)
pBAR.Value = pBAR.Value + 1
s.WriteLine(buff)
rSNAP.MoveNext()
End While
s.Close()
rSNAP.Close()
rSNAP = Nothing
End If

This implementation however is very slow taking almost an hour to write 250,000 instead of the original 2 or 3 minutes! the loop and everything else is just as fast, it is the writeline function that is comparitvley very slow compared to the original print function in vb6 (which is no longer present as far as im aware in .NET)

Can anyone suggest a faster way of writing to a file line by line?
 
Back
Top