How to validate CSV in C#?
c#, csv
Solution
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
}
}
}
Problem
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); ```