65.9K
CodeProject is changing. Read more.
Home

Validate a CSV file in VB.NET

starIconstarIconstarIcon
emptyStarIcon
starIcon
emptyStarIcon

3.38/5 (5 votes)

Oct 23, 2011

CPOL
viewsIcon

31945

Code to validate a CSV file in VB.NET.

Here is how to validate a CSV file:

Dim reader As StreamReader = New StreamReader(strFilePath)
Try
    Dim j As Integer = 0
    Dim i As Integer

    If reader.EndOfStream Then
        MessageBox.Show("The CSV file is empty, please update", _
                        "Error", MessageBoxButtons.OK)
        Application.Exit()
    End If

    While Not reader.EndOfStream
        'Dim s As String = reader.ReadLine()
        Dim lineContents() As String = Split(reader.ReadLine(), ",")
        Dim NoOfCol As Integer

        j = j + 1
        If j = 1 Then
            NoOfCol = lineContents.Length
        End If
        If NoOfCol = lineContents.Length Then
            For i = 0 To lineContents.Length - 1
                'Dim str As String = lineContents(i)
                If Trim(lineContents(i)).Length = 0 Then
                    'alert user here.... and exit???
                    Dim Response As DialogResult = _
                       MessageBox.Show("Null value found at row " & j & _
                        ", column " & (i + 1) & vbCrLf & _
                        "Do you want to Continue?", _
                        "CSV File Confirmation", MessageBoxButtons.YesNo)
                    If Response = DialogResult.No Then
                        Application.Exit()
                    End If
                End If
            Next
        Else
            MessageBox.Show("Error: Row " & j & _
              " has invalid number of columns", _
              "CSV File Error", MessageBoxButtons.OK)
            Application.Exit()
        End If
    End While