如何用字符串列表验证输入文件?

时间:2019-04-17 13:07:25

标签: c# dynamic csvhelper

我需要写一个文件,但是由于我没有声明的类型(我使用的是动态对象),所以我只有一个字符串模式,例如id;name;address。 如何使用此架构验证输入流?

之所以使用动态数据,是因为系统不需要了解这些数据。

但是需要检查数据是否遵循提供的模式。

基本上需要重写此扩展方法

public static void Write<T>(this string filepath, System.Collections.Generic.IEnumerable<T> records, string delimiter = "\t")
{
    var config = new CsvHelper.Configuration.Configuration { Delimiter = delimiter };

    using (var writer = new System.IO.StreamWriter(filepath))
    using (var csv = new CsvHelper.CsvWriter(writer, config))
        csv.WriteRecords(records); 
}

并为架构添加参数

1 个答案:

答案 0 :(得分:0)

我假设您指的是通用对象,而不是动态对象。

如果您要确保记录的名称与架构列表完全相同,则可以这样做。

public static void Write<T>(string filepath, System.Collections.Generic.IEnumerable<T> records, string schema, string delimiter = "\t")
{
    var properties = typeof(T).GetProperties();

    var schemaList = schema.Split(';');

    if (properties.Count() != schemaList.Count())
    {
        throw new Exception("The given class does not have the same number of properties as the schema");
    }

    foreach (var name in schemaList)
    {
        if (!properties.Any(p => p.Name.ToUpper() == name.ToUpper()))
        {
            throw new Exception($"The given class is missing the property '{name}'");
        }
    }

    var config = new CsvHelper.Configuration.Configuration { Delimiter = delimiter };

    using (var writer = new System.IO.StreamWriter(filepath))
    using (var csv = new CsvHelper.CsvWriter(writer, config))
    {
        csv.WriteRecords(records);
    }
}

如果您要确保记录中的记录最少包含模式中的属性名称,但是您不关心它们是否具有额外的属性,并且不希望写入这些额外的属性,则可以使用{{ 1}}进行设置。

DefaultClassMap