Chat LIVE With Programming Experts! There Are 23 Online Right Now...

Welcome to Dream.In.Code
Become a VB.NET Expert!

Join 244,295 VB.NET Programmers for FREE! Get instant access to thousands of VB.NET experts, tutorials, code snippets, and more! There are 896 people online right now. Registration is fast and FREE... Join Now!




Importing Text file Data to Array

 
Reply to this topicStart new topic

Importing Text file Data to Array

hillbma
26 Dec, 2008 - 08:27 AM
Post #1

New D.I.C Head
*

Joined: 8 Dec, 2008
Posts: 8



Thanked: 1 times
My Contributions
Good day,

I am having an issue importing text data into an array. The text data is in the following tab-delimited format (cost type accountcode):

0.60 Duplicating 2780100
0.20 Duplicating 2975650
0.20 Duplicating 3190200
1.20 Duplicating 3370850

My goal is to import the data into an array, run through the data, totaling up any costs where the account code, for example "2780100" matches, and then export the data back to a text file with only one instance of each account code with the total cost associated with that account.

This is a work in progress. Right now I am just trying to import the data, and then export it to check on my parsing. The code does not show any errors, but when I run it, I get a first chance exception error, and nothing is imported or exported.

Can anyone help me to see the errors of my ways?

CODE
Option Explicit On
Option Strict On

Public Class MainForm

    Public filecontents As String

    Private Sub MainForm_Load(ByVal sender As Object, ByVal e As System.EventArgs) Handles Me.Load

        ' load from the text file the product item numbers nad prices

        ' declare the variables used
        Dim inputfile As String = "C:\Visual Studio 2005\Projects\SummarizeExports\SummarizeExports\bin\Debug\Exports.txt"



        ' check to make sure the file exists, and if yes then
        ' get the contents of the file. If not, display message.

        If My.Computer.FileSystem.FileExists(inputfile) Then
            filecontents = My.Computer.FileSystem.ReadAllText(inputfile)

            Call Process_Export_File()

        Else
            MessageBox.Show("File does not exist", "Exports.txt", _
                MessageBoxButtons.OK, MessageBoxIcon.Information)

        End If



        ' close the application
        Me.Close()

    End Sub

    Private Sub Process_Export_File()
        ' dimension array to store each line in the Exports.txt file


        Dim counter As Integer = 0
        Dim lineindex As Integer
        Dim transaction() As String = Split(filecontents, vbCrLf)
        Dim cost(lineindex) As String
        Dim client(lineindex) As String
        Dim duplicating As String = "Duplicating"
        Dim position As Integer = 1
        Dim newposition As Integer


        ' find first newline in string
        lineindex = filecontents.IndexOf(ControlChars.NewLine)

        ' run through data to store each transaction in the transaction array
        Do Until lineindex - counter <= 0
            position = transaction(counter).IndexOf("Duplicating", 0)
            newposition = position + 11

            ' get the cost value of the transaction
            cost(counter) = transaction(counter).Substring(1, position)
            cost(counter) = cost(counter).Trim

            ' get the client number for the transaction
            client(counter) = transaction(counter).Substring(newposition, 6)
            client(counter) = client(counter).Trim

            Const File As String = "TestExport.txt"
            My.Computer.FileSystem.WriteAllText(File, _
            cost(counter) & _
            " " & duplicating & _
            " " & client(counter) & _
            ControlChars.NewLine, True)

            ' update the counter and loop
            counter = counter + 1


        Loop
    End Sub

End Class


User is offlineProfile CardPM
+Quote Post


n8wxs
RE: Importing Text File Data To Array
26 Dec, 2008 - 10:20 AM
Post #2

--... ...-- -.. . -. ---.. .-- -..- ...
Group Icon

Joined: 6 Jan, 2008
Posts: 1,609



Thanked: 223 times
My Contributions
You have declared the arrays as zero sized.
CODE

Dim cost(lineindex) As String
Dim client(lineindex) As String

So the second access cost(counter) = transaction(counter).Substring(1, position) results in an IndexOutOfRangeException because counter is 1.

Since you are splitting the file contents line by line, Dim transaction() As String = Split(filecontents, vbCrLf), the loop you are using that finds the line terminations is unnecessary. I would loop on the length the transaction[] array.

Here's how I did your Process_Export_File() subroutine. Since there may/will be multiple lines with the same account code, I used an ArrayList to hold the Exports.txt file contents. I changed the order of the fields on the file lines so that the account code is the first field before copying the line to the ArrayList. When the ArrayList is sorted after all the file contents have been copied to it, all the lines with the same account codes will be grouped together in the ArrayList. Making it easy to process! smile.gif
CODE

    Private Sub Process_Export_File()
        Const File As String = "TestExport.txt"

        Dim accountCode As String
        Dim cost As Decimal
        Dim fields() As String
        Dim fileData As ArrayList = New ArrayList
        Dim lineContent As String
        Dim name As String
        Dim reorderedLine As String
        Dim transaction() As String = Split(filecontents, vbCrLf)

        For Each lineContent In transaction
            'ignore blank lines
            If lineContent.Length = 0 Then
                Continue For
            End If
            'split the line into it's fields: cost, name, code
            fields = Split(lineContent, vbTab)
            'reverse the field order so account code is first
            reorderedLine = fields(2) & vbTab & fields(1) & vbTab & fields(0)
            'add to list
            fileData.Add(reorderedLine)
        Next
        ' sort the list, multiple account codes will now be grouped together
        fileData.Sort()
        'copy the first string in the list
        reorderedLine = fileData.Item(0).ToString()
        'split it back to fields
        fields = Split(reorderedLine, vbTab)
        'save the individual items
        accountCode = fields(0)
        name = fields(1)
        cost = 0
        'loop on the arraylist contents
        For Each reorderedLine In fileData
            'back to fields
            fields = Split(reorderedLine, vbTab)
            'if this line has the same account code, add the cost to running total
            If fields(0) = accountCode Then
                cost += Decimal.Parse(fields(2))
            Else
                'save the previous account code information
                lineContent = accountCode + vbTab + name + vbTab + cost.ToString() + vbNewLine
                'write line to file, appending it
                My.Computer.FileSystem.WriteAllText(File, lineContent, True)
                'save current information
                accountCode = fields(0)
                name = fields(1)
                cost = Decimal.Parse(fields(2))
            End If

        Next
        'save the last account code information
        lineContent = accountCode + vbTab + name + vbTab + cost.ToString() + vbNewLine
        'write line to file, appending it
        My.Computer.FileSystem.WriteAllText(File, lineContent, True)

    End Sub


This post has been edited by n8wxs: 26 Dec, 2008 - 12:12 PM
User is offlineProfile CardPM
+Quote Post

hillbma
RE: Importing Text File Data To Array
29 Dec, 2008 - 12:38 PM
Post #3

New D.I.C Head
*

Joined: 8 Dec, 2008
Posts: 8



Thanked: 1 times
My Contributions

Thank you for your time! You really did look into this and I appreciate it!

Unfortunately, I am still getting a first chance exception error and the text file is not processing. So, I am now wondering if the problem isn't with the code, but with either my PC (running Vista) or VB.NET version (2005). The first chance exception error I am getting is on the line of code that references the array:

CODE

  reorderedLine = fields(2) & vbTab & fields(1) & vbTab & fields(0)


The error is IndexOutofRangeException was unHandled. Do you get the same error if you try and run the code? OR, is the code just fine, but I need to add some error handling into it so that it will run?

Thank you!


User is offlineProfile CardPM
+Quote Post

n8wxs
RE: Importing Text File Data To Array
29 Dec, 2008 - 02:57 PM
Post #4

--... ...-- -.. . -. ---.. .-- -..- ...
Group Icon

Joined: 6 Jan, 2008
Posts: 1,609



Thanked: 223 times
My Contributions
QUOTE(hillbma @ 29 Dec, 2008 - 12:38 PM) *

CODE

  reorderedLine = fields(2) & vbTab & fields(1) & vbTab & fields(0)

The error is IndexOutofRangeException was unHandled. Do you get the same error if you try and run the code? OR, is the code just fine, but I need to add some error handling into it so that it will run?

Thank you!

No, I don't get that error. Of course, the only data I had to work with is the original 4 example lines you gave in your post. smile.gif

The error is indicating the string that was split into the fields array does not have at least 3 tokens. So it doesn't fit with the file line layout you posted in your original message. The line that's failing must be missing it's cost, type or account code. You could check that the fields array length is 3 and output the bad line to a MessageBox so you can see it when the length is wrong, and then skip adding the bad line to the fileData ArrayList.
CODE

...
//'split the line into it's fields: cost, name, code
fields = Split(lineContent, vbTab)
//'All three tokens present?
if fields.Length() = 3 then
    //'reverse the field order so account code is first
    reorderedLine = fields(2) & vbTab & fields(1) & vbTab & fields(0)
    //'add to list
    fileData.Add(reorderedLine)
Else
    //'Bad data
    MessageBox.Show("Bad data line - " + lineContent)
End If
...


This post has been edited by n8wxs: 29 Dec, 2008 - 02:59 PM
User is offlineProfile CardPM
+Quote Post

hillbma
RE: Importing Text File Data To Array
30 Dec, 2008 - 06:47 AM
Post #5

New D.I.C Head
*

Joined: 8 Dec, 2008
Posts: 8



Thanked: 1 times
My Contributions
Yes, that was exactly it. I had edited, about a week ago, the text file I was using so the code couldn't handle what I had added to the beginning. Thank you very much for all of your help with this!
User is offlineProfile CardPM
+Quote Post

hunpol
RE: Importing Text File Data To Array
3 May, 2009 - 12:40 AM
Post #6

New D.I.C Head
*

Joined: 20 Jan, 2009
Posts: 1

QUOTE(hillbma @ 30 Dec, 2008 - 06:47 AM) *

Yes, that was exactly it. I had edited, about a week ago, the text file I was using so the code couldn't handle what I had added to the beginning. Thank you very much for all of your help with this!



Hello!! I'm doing the same thing as you.I am storing Locations and its coordinates in a textfile.I am having the same error as you had.Can you tel me how u edited the data in the textfile so that it could be read?
User is offlineProfile CardPM
+Quote Post

Fast ReplyReply to this topicStart new topic

Time is now: 7/4/09 04:31PM

Live VB.NET Help!

Be Social

Dream.In.Code RSS Feed Dream.In.Code LinkedIn Group Follow Us On Twitter Fan Us On Facebook

VB.NET Tutorials

Reference Sheets

VB.NET Snippets

DIC Chatroom

Bye Bye Ads

Monthly Drawing

Thumb Drive

Top Contributors

Top 10 Kudos This Month