我们在一些应用程序中使用 FlatFile 库 (https://github.com/forcewake/FlatFile( 来解析一些用分隔符 (";"( 分隔的文件,因为很多时候都没有问题。
我们昨天遇到了一个问题,即接收行尾有多个字段为空的文件。
我用简短的控制台应用程序复制了这个问题,以显示并允许您以简单的方式进行验证:
using FlatFile.Delimited;
using FlatFile.Delimited.Attributes;
using FlatFile.Delimited.Implementation;
using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
namespace FlatFileTester
{
class Program
{
static void Main(string[] args)
{
var layout = GetLayout();
var factory = new DelimitedFileEngineFactory();
using (MemoryStream ms = new MemoryStream())
using (FileStream file = new FileStream(@"D:shareddotnetFlatFileTestertest.csv", FileMode.Open, FileAccess.Read))
{
byte[] bytes = new byte[file.Length];
file.Read(bytes, 0, (int)file.Length);
ms.Write(bytes, 0, (int)file.Length);
var flatFile = factory.GetEngine(layout);
ms.Position = 0;
List<TestObject> records = flatFile.Read<TestObject>(ms).ToList();
foreach(var record in records)
{
Console.WriteLine(string.Format("Id="{0}" - DescriptionA="{1}" - DescriptionB="{2}" - DescriptionC="{3}"", record.Id, record.DescriptionA, record.DescriptionB, record.DescriptionC));
}
}
Console.ReadLine();
}
public static IDelimitedLayout<TestObject> GetLayout()
{
IDelimitedLayout<TestObject> layout = new DelimitedLayout<TestObject>()
.WithDelimiter(";")
.WithQuote(""")
.WithMember(x => x.Id)
.WithMember(x => x.DescriptionA)
.WithMember(x => x.DescriptionB)
.WithMember(x => x.DescriptionC)
;
return layout;
}
}
[DelimitedFile(Delimiter = ";", Quotes = """)]
public class TestObject
{
[DelimitedField(1)]
public int Id { get; set; }
[DelimitedField(2)]
public string DescriptionA { get; set; }
[DelimitedField(3)]
public string DescriptionB { get; set; }
[DelimitedField(4)]
public string DescriptionC { get; set; }
}
}
这是文件的示例:
1;desc1;desc1;desc1
2;desc2;desc2;desc2
3;desc3;;desc3
4;desc4;desc4;
5;desc5;;
因此,前 4 行按预期解析:
- 第一行和第二行中值的所有字段
- 第三行的第三个字段的空字符串
- 第四行的 fouth 字段的空字符串
在第五行中,我们期望在第三和第四字段中为空字符串,如下所示:
Id=5
DescriptionA="desc5"
DescriptionB=""
DescriptionC=""
相反,我们收到这个:
Id=5
DescriptionA="desc5"
DescriptionB=";" // --> THE SEPARATOR!!!
DescriptionC=""
我们无法理解是配置问题、库错误还是代码中的其他问题......
任何人都对这个库有一些类似的经历,或者可以注意到上面的代码中的一些问题没有与库链接,但导致了错误......?
我看了一下并调试了开源库的源代码:https://github.com/forcewake/FlatFile。
似乎有一个问题,特别是在这种情况下,在 witch 中有 2 个空字段,在一行的末尾,错误在最后一行之前对字段生效。
我为这个图书馆打开了一个问题,希望图书馆的一些贡献者可以花一些时间来调查,如果是这样,修复:https://github.com/forcewake/FlatFile/issues/80
现在我们决定修复列表的错误值,如下所示:
string separator = ",";
//...
//...
//...
records.ForEach(x => {
x.DescriptionC = x.DescriptionC.Replace(separator, "");
});
无论如何,对于我们的情况,将对应于分隔符的字符作为该字段的值是没有意义的......
。即使最好修复库的错误