Question Another Array question...

popeye2755

New member
Joined
Aug 29, 2010
Messages
3
Programming Experience
Beginner
Hi Guys,

I'm new to this so please go easy...!!! OK, I'm working on a small project that at one point requires me to plot a graph using set of XY data points. The points are contained within a CSV text file, a small example is attached. The problem I'm having is that the custom control I'm using cannot read directly from the CSV file, it can only read from an Array defined as a double. No matter what I do, I can't get the code to read the CSV file and dump it into the array so that the control can read it. Can anyone help?
 

Attachments

  • OIA2.txt
    1.7 KB · Views: 24
read in the file

read the file line by line

parse each line to a Point (this looks to be points seeing as you have the comma). See Point.Parse(...) (note there is a couple different Point structures in .Net, you can also just manually parse to a point by splitting at "," and parsing each double with Double.Parse)

add the point to a List (or some collection as they can grow dynamically)

convert the list to an array... List.ToArray
 
You could do something like this:

VB.NET:
Imports System.IO
Imports System.Drawing

'Point info
Public Structure CanvasPoint
    Public X As Double
    Public Y As Double
End Structure

Public Class PointsReader

    Public Shared Function ReadPoints(ByVal filePath As String) As CanvasPoint()

        'Read the file into this list
        Dim lines As New List(Of String)

        'File reading
        Using sr As New StreamReader(filePath)
            While Not sr.EndOfStream
                Dim line As String = sr.ReadLine
                If Not String.IsNullOrEmpty(line) Then lines.Add(line)
            End While
        End Using

        Dim points(lines.Count) As CanvasPoint
        Dim cp As CanvasPoint
        Dim splits() As String
        Dim x As Double
        Dim y As Double

        For i As Integer = 0 To lines.Count - 1
            Dim a As String = lines(0) 'get the line
            splits = lines(i).Split(",") 'split it at comma (,)
            x = Double.Parse(splits(0)) 'parse the x-coordinate
            y = splits(1) 'parse the y-coordinate
            cp.X = x 'put x into point
            cp.Y = y 'put y into point

            points(i) = cp '
        Next

        Return points
    End Function

End Class


use it as follows:

VB.NET:
Dim points() As CanvasPoint = PointsReader.ReadPoints("C:\OIA2.txt")

        For Each p As CanvasPoint In points
            Console.WriteLine(String.Format("{0}, {1}", p.X, p.Y))
        Next
 
Back
Top