如何在C#中验证CSV? [英] How to validate CSV in C#?

查看:155
本文介绍了如何在C#中验证CSV?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在.NET中有一个内置的方法来验证csv文件/字符串?

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

我喜欢像这个在线csv验证器,但在C#。我做了一些研究,但我所有的发现是人们编写代码本身的例子(例子都是几年前写的,可能已过时)。

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);


推荐答案

由于某种原因,它埋在VB命名空间中,但它是.NET Framework的一部分,你只需要添加一个对Microsoft.VisualBasic程序集的引用。您要查找的类型是 TextFieldParser

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
        }
    }
}

这篇关于如何在C#中验证CSV?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆