Click here to Skip to main content
65,938 articles
CodeProject is changing. Read more.
Articles / Languages / VB

Validate a CSV file in VB.NET

3.38/5 (5 votes)
23 Oct 2011CPOL 31.9K  
Code to validate a CSV file in VB.NET.

Here is how to validate a CSV file:


VB
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

License

This article, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)