Home
Search
 
What's New
Index
Books
Links
Q & A
Newsletter
Banners
 
Feedback
Tip Jar
 
C# Helper...
 
XML RSS Feed
Follow VBHelper on Twitter
 
 
 
MSDN Visual Basic Community
 
 
 
 
 
 
TitleMake a file containing a list of numbers in two ways in VB .NET.
DescriptionThis example shows how to make a file containing a list of numbers in two ways in VB .NET. It makes the file using a StreamWriter one line at a time. It then makes the file by building the file's contents in a StringBuilder and then writing the result into a StreamWriter. It compares the speeds of these methods.
Keywordsarray, file, I/O, IO, StreamWriter, StringBuilder
CategoriesFiles and Directories
 
When the user clicks the StreamWriter button, the program uses a StreamWriter to write numbers into the file one line at a time.
 
Private Sub btnStreamWriter_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnStreamWriter.Click
    Dim start_time As Date = Now

    ' Open the file.
    Dim stream_writer As New StreamWriter(txtFile.Text)

    ' Write the numbers.
    Dim rand As New Random
    Dim num As Integer = Integer.Parse(txtNumNumbers.Text)
    For i As Integer = 1 To num
        stream_writer.WriteLine(rand.Next(0, _
            100000).ToString)
    Next i
    stream_writer.Close()

    Dim stop_time As Date = Now
    Dim elapsed_time As TimeSpan = _
        stop_time.Subtract(start_time)
    lblStreamWriter.Text = _
        elapsed_time.TotalSeconds.ToString("0.0000")
End Sub
 
When the user clicks the StringBuilder button, the program generates the file's contents in a StringBuilder and then writes the whole thing at once into a StreamWriter.
 
Private Sub btnStringBuilder_Click(ByVal sender As _
    System.Object, ByVal e As System.EventArgs) Handles _
    btnStringBuilder.Click
    Dim start_time As Date = Now

    ' Build a string containing all of the numbers.
    Dim rand As New Random
    Dim num As Integer = Integer.Parse(txtNumNumbers.Text)
    ' Allow 7 characters per number: 5 digits plus vbCRrLf.
    Dim string_builder As New StringBuilder(num * 7)

    For i As Integer = 1 To num
        string_builder.Append(rand.Next(0, 100000).ToString)
        string_builder.Append(vbCrLf)
    Next i

    ' Write the string into the file.
    Dim stream_writer As New StreamWriter(txtFile.Text)
    stream_writer.Write(string_builder.ToString)
    stream_writer.Close()

    Dim stop_time As Date = Now
    Dim elapsed_time As TimeSpan = _
        stop_time.Subtract(start_time)
    lblStringBuilder.Text = _
        elapsed_time.TotalSeconds.ToString("0.0000")
End Sub
 
In my tests, the difference between these methods is very small. The StringBuilder version may be a few percent faster. Because the difference is so small, you should use whichever version is easier to understand.
 
 
Copyright © 1997-2010 Rocky Mountain Computer Consulting, Inc.   All rights reserved.
  Updated