我正在使用Filehelpers并导入了一个csv文件。一切正常,但现在我想验证导入的字段的长度。
[DelimitedRecord(";")]
public class ImportFile
{
public string Name;
public string NameSurname;
}
是否有可能的方法,我可以创建一个属性" MaxLength"如果InputString大于我的MaxLength Attribut,它会拆分输入字符串或抛出异常? 我发现的唯一的东西是FieldFlixedLength,但那只是Split,输入文件在字段中。
答案 0 :(得分:0)
您可以按如下方式实施AfterRead
事件:
[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();
}
}