将 OmegaMan 的解决方案应用于 FileHelpers 并不容易,但以下内容可能会帮助您入门。
暂时假设您只有一条记录。然后以下工作:
[DelimitedRecord(":")]
public class ImportRecord
{
[FieldTrim(TrimMode.Both)]
public string Key;
[FieldTrim(TrimMode.Both)]
public string Value;
}
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<ImportRecord>();
string fileAsString = @"custID: 1732" + Environment.NewLine +
@"name: Juan Perez" + Environment.NewLine +
@"balance: 435.00" + Environment.NewLine +
@"date: 11-05-2002" + Environment.NewLine;
ImportRecord[] validRecords = engine.ReadString(fileAsString);
var dictionary = validRecords.ToDictionary(r => r.Key, r => r.Value);
Assert.AreEqual(dictionary["custID"], "1732");
Assert.AreEqual(dictionary["name"], "Juan Perez");
Assert.AreEqual(dictionary["balance"], "435.00");
Assert.AreEqual(dictionary["date"], "11-05-2002");
Console.ReadKey();
}
}
但是,一旦您有多个记录,您就会得到重复的字典条目,而上述方法将不起作用。但是有一些方法可以解决这个问题。例如,如果每条记录的行数相同(在您的示例中为 4,您可以这样做)
[DelimitedRecord(":")]
[IgnoreEmptyLines()]
public class ImportRecord
{
[FieldTrim(TrimMode.Both)]
public string Key;
[FieldTrim(TrimMode.Both)]
public string Value;
}
public class Customer
{
public string Id { get; set; }
public string Name { get; set; }
public string Balance { get; set; }
public string Date { get; set; }
}
class Program
{
static void Main(string[] args)
{
var engine = new FileHelperEngine<ImportRecord>();
string fileAsString =
@"custID: 1732
name: Juan Perez
balance: 435.00
date: 11-05-2002
custID: 554
name: Pedro Gomez
balance: 12342.30
date: 06-02-2004";
ImportRecord[] validRecords = engine.ReadString(fileAsString);
var customers = validRecords
.Batch(4, x => x.ToDictionary(r => r.Key, r => r.Value))
.Select(dictionary => new Customer()
{
Id = dictionary["custID"],
Name = dictionary["name"],
Balance = dictionary["balance"],
Date = dictionary["date"]
}).ToList();
Customer customer1 = customers[0];
Assert.AreEqual(customer1.Id, "1732");
Assert.AreEqual(customer1.Name, "Juan Perez");
Assert.AreEqual(customer1.Balance, "435.00");
Assert.AreEqual(customer1.Date, "11-05-2002");
Customer customer2 = customers[1];
Assert.AreEqual(customer2.Id, "554");
Assert.AreEqual(customer2.Name, "Pedro Gomez");
Assert.AreEqual(customer2.Balance, "12342.30");
Assert.AreEqual(customer2.Date, "06-02-2004");
Console.WriteLine("All OK");
Console.ReadKey();
}
}
}
另一种选择是预先解析内容,以便将其转换为更传统的 CSV 文件。也就是说,使用File.ReadAllText() 得到string,然后用字段分隔符替换换行符,用换行符替换空行。然后用FileHelpersEngine.ReadAsString()读取转换后的字符串。