我们在一些应用程序中使用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:\shared\dotnet\FlatFileTester\test.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行按预期进行解析:
在第五行中,我们期望第三和第四字段上的字符串为空,如下所示:
Id=5
DescriptionA="desc5"
DescriptionB=""
DescriptionC=""相反,我们收到的是:
Id=5
DescriptionA="desc5"
DescriptionB=";" // --> THE SEPARATOR!!!
DescriptionC=""我们无法理解是否是配置问题、库错误或代码中的其他问题.
有人对这个库有类似的经验,或者在上面的代码中注意到一些问题,不是链接到库,而是导致错误.?
发布于 2018-09-07 15:55:54
我查看并调试了开源库的源代码:https://github.com/forcewake/FlatFile。
似乎存在一个问题,特别是在这种情况下,在这里有两个空字段,在一行的末尾,bug会在行的最后一个字段上生效。
我为这个libray打开了一个问题,希望库的一些贡献者能够投入一些时间进行调查,如果是的话,可以修复:https://github.com/forcewake/FlatFile/issues/80。
现在,我们决定修复列表的错误值,如下所示:
string separator = ",";
//...
//...
//...
records.ForEach(x => {
x.DescriptionC = x.DescriptionC.Replace(separator, "");
});无论如何,对于我们的情况,将一个字符对应于分隔符作为该字段的值是没有意义的.
如果对库进行错误修复会更好,则为...even。
https://stackoverflow.com/questions/52017242
复制相似问题