首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Filehelpers字段最大长度

Filehelpers字段最大长度
EN

Stack Overflow用户
提问于 2015-01-22 10:49:31
回答 1查看 1.2K关注 0票数 1

我正在使用Filehelpers并导入一个csv文件。一切都很好,但是现在我想验证导入字段的长度。

代码语言:javascript
复制
[DelimitedRecord(";")]
public class ImportFile
{
    public string Name;
    public string NameSurname;
}

如果MaxLength大于InputString,那么是否有可能创建一个属性"MaxLength“来拆分输入字符串或抛出异常?我发现的唯一东西是FieldFlixedLength,但这只是字段中的Inputfile。

EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2015-01-26 15:40:35

您可以按以下方式实现AfterRead事件:

代码语言:javascript
复制
[DelimitedRecord(";")]
public class ImportRecord : INotifyRead<ImportRecord>
{
    public string Name;         
    public string NameSurname;

    public void BeforeRead(BeforeReadEventArgs<ImportRecord> e)
    {
    }

    public void AfterRead(AfterReadEventArgs<ImportRecord> e)
    {
        if (e.Record.Name.Length > 20)
            throw new Exception("Line " + e.LineNumber + ": First name is too long");

        if (e.Record.NameSurname.Length > 20)
            throw new Exception("Line " + e.LineNumber + ": Surname name is too long");
    }

}

class Program
{
    static void Main(string[] args)
    {
        var engine = new FileHelperEngine<ImportRecord>();
        engine.ErrorMode = ErrorMode.SaveAndContinue;

        string fileAsString = "Firstname;SurnameIsAVeryLongName" + Environment.NewLine
                            + "FirstName;SurnameIsShort";

        ImportRecord[] validRecords = engine.ReadString(fileAsString);

        Console.ForegroundColor = ConsoleColor.Red;
        foreach (ErrorInfo error in engine.ErrorManager.Errors)
        {
            Console.WriteLine(error.ExceptionInfo.Message);
        }

        Console.ForegroundColor = ConsoleColor.White;            
        foreach (ImportRecord validRecord in validRecords)
        {
            Console.WriteLine(String.Format("Successfully read record: {0} {1}", validRecord.Name, validRecord.NameSurname));
        }

        Console.WriteLine("Press any key...");
        Console.ReadKey();
    }
}
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/28086887

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档