我正在使用Filehelpers并导入一个csv文件。一切都很好,但是现在我想验证导入字段的长度。
[DelimitedRecord(";")]
public class ImportFile
{
public string Name;
public string NameSurname;
}如果MaxLength大于InputString,那么是否有可能创建一个属性"MaxLength“来拆分输入字符串或抛出异常?我发现的唯一东西是FieldFlixedLength,但这只是字段中的Inputfile。
发布于 2015-01-26 15:40:35
您可以按以下方式实现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();
}
}https://stackoverflow.com/questions/28086887
复制相似问题