使用 FileHelpers.dll 3.0.1.0 版和 .net 4.0。
重现问题的代码:
像这样创建一个文件 Accounts.txt:
"AccountName","ExtraColumn"
"MR GREEN ","abc"
"MR SMITH ","def"
c# 账户类:
[IgnoreFirst(1)]
[DelimitedRecord(",")]
[IgnoreEmptyLines()]
public class Account
{
[FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
public string AccountName;
}
读取文件:
string fname = @"C:\test\Accounts.txt";
FileHelperEngine engine = new FileHelperEngine(typeof(Account));
Account[] importNodes = (Account[])engine.ReadFile(fname); // XX
现在,我预计会在第 XX 行引发异常,因为文件 (2) 中的列多于“帐户”类 (1) 中的列。但是,没有出现异常,额外的列似乎被默默地忽略了。
如果您更改 Account 类以删除“FieldQuoted”属性,那么确实会引发异常,例如:
[FileHelpers.BadUsageException] {"Line: 2 Column: 0. Delimiter ',' found after the last field 'AccountName' (the file is wrong or you need to add a field to the record class)"} FileHelpers.BadUsageException
谁能提供一些见解?具有 FieldQuoted 属性的代码确实应该引发异常吗?我做错了什么吗?
编辑:是否有任何解决方法,以便当输入文件中的列数多于预期时会引发错误?
最佳答案
[IgnoreFirst(1)]
忽略文件的第一行,而不是第一列。
请参阅此处的说明:IgnoreFirstAttribute
删除 FieldQuoted
会导致错误,因为您引用了没有此属性就无法正确处理的字段。
FileHelpers
库只是忽略文件中在您的类中没有相应字段的字段。
要忽略每行中的第一个字段,您可以像这样在类定义中添加一个虚拟字段:
[IgnoreFirst(1)]
[DelimitedRecord(",")]
[IgnoreEmptyLines()]
public class Account
{
[FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
public string AccountName;
[FieldValueDiscarded]
[FieldQuoted('"', QuoteMode.OptionalForBoth, MultilineMode.NotAllow)]
public string Dummy;
}
作为解决方法,我建议在末尾添加一个普通的 string
虚拟字段。然后您可以检查此字段是否填写在 FileHelperEngine.AfterReadRecord
中并抛出如下异常:
FileHelperEngine engine = new FileHelperEngine(typeof(Account));
engine.AfterReadRecord += engine_AfterReadRecord;
try
{
Account[] importNodes = (Account[])engine.ReadFile(fname); // XX
}
catch (Exception e)
{
}
static void engine_AfterReadRecord(EngineBase engine, FileHelpers.Events.AfterReadEventArgs<object> e)
{
if (!string.IsNullOrEmpty(((Account) e.Record).Dummy))
{
throw new ApplicationException("Unexpected field");
}
}
关于c# - FileHelpers - 文件中的额外列在使用 FieldQuoted 属性时不会引发错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25008873/