Visual Studio 2013 Lesson : Import TXT file

[Lesson 40] <<[Contents] >>[Lesson 42]

Import TXT file

Visual Studio features a command line that allows data to be imported from various file types.
Streamreader reads the files and adds the data to assigned objcets, strings or arrays.

The coding shown imports a TXt (text file). Note the data in the text file is separated to smaller strings using the (,) comma.
The following coding imports a TXT file,assigns each

'importing this allows us to use streamwriter without typing import System.io before each instance of StreamWriter
Imports System.IO
'public class form
Public Class Form1
‘Declare variables for use in whole program Universal variables”
Dim Array1() As String
Dim Array2() As String


'Read data from external file
Private Sub Button1_Click(sender As Object, e As EventArgs) Handles Button1.Click
'Use IO reader to open file, identify file name and path).
Using ioReader As New Microsoft.VisualBasic.FileIO.TextFieldParser("G:\Folder\TXT_folder\Test.txt")
'Identify the file as a comma delimited file

ioReader.TextFieldType = FileIO.FieldType.Delimited
ioReader.SetDelimiters(",")

While Not ioReader.EndOfData
'declare variable “arrCurrentRow as a string field for IO reader
Dim arrCurrentRow As String() = ioReader.ReadFields()

    If Array1 Is Nothing Then
‘ ReDim statement to change the size of one or more dimensions of an array that has already been declared.
    ReDim Preserve Array1(0)
    ReDim Preserve Array2(0)

‘ assign strings form array to different rows
    Array1(0) = arrCurrentRow(0)
    Array2(0) = arrCurrentRow(1)

    Else
‘assign size to the length of the string
    ReDim Preserve Array1(Array1.Length)
    ReDim Preserve Array2(Array2.Length)

‘assign the length of the string to the length – 1, to allow for fact that array numbering starts at 0
    Array1((Array1.Length - 1)) = arrCurrentRow(0)
    Array2((Array2.Length - 1)) = arrCurrentRow(1)

End If

End While
End Using

‘ read the string according to assigned rows and add to listBoxes identified. This shows each column of the data file in a different list box
ListBox1.Items.Clear()
    For Each obj As Object In Array1
        ListBox1.Items.Add(obj)
    Next
        ListBox2.Items.Clear()
    For Each obj2 As Object In Array2
        ListBox2.Items.Add(obj2)
    Next

End Sub


[Lesson 40] <<[Contents] >>[Lesson 42]