Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to validate CSV in C#?

Tags:

c#

csv

Is there a built-in method in .NET that validates csv files/strings?

I would prefer something like this online csv validator but in C#. I have done some research but all I have found are examples of people writing the code themselves (examples were all written a few years ago and might be outdated).

POC:

bool validCSV = CoolCSV_ValidatorFunction(string csv/filePath);
like image 957
user3772119 Avatar asked Jul 15 '14 18:07

user3772119


People also ask

What is CSV Validator?

CSV Validator is a CSV validation and reporting tool which implements CSV Schema Language . Released as Open Source under the Mozilla Public Licence version 2.0. This page is for CSV Validator 1.1 (and related minor releases), the equivalent page for the previous 1.0 release is now to be found at csv-validator-1.0.

How do I validate a csv file in Python?

I.e., if you want to validate data from a CSV file, you have to first construct a CSV reader using the standard Python csv module, specifying the appropriate dialect, and then pass the CSV reader as the source of data to either the CSVValidator. validate or the CSVValidator. ivalidate method.


2 Answers

There is! For some reason it's buried in the VB namespace, but it's part of the .NET Framework, you just need to add a reference to the Microsoft.VisualBasic assembly. The type you're looking for is TextFieldParser.

Here is an example of how to validate your file:

using Microsoft.VisualBasic.FileIO;
...
var path = @"C:\YourFile.csv";
using (var parser = new TextFieldParser(path))
{
    parser.TextFieldType = FieldType.Delimited;
    parser.SetDelimiters(",");

    string[] line;
    while (!parser.EndOfData)
    {
        try
        {
            line = parser.ReadFields();
        }
        catch (MalformedLineException ex)
        {
            // log ex.Message
        }
    }
}
like image 175
Justin R. Avatar answered Sep 23 '22 20:09

Justin R.


The best CSV reader I've found is this one from Lumenworks:

http://www.codeproject.com/Articles/9258/A-Fast-CSV-Reader

Very fast, very full-featured. Recommended.

like image 34
Ken Smith Avatar answered Sep 22 '22 20:09

Ken Smith