简体   繁体   中英

Error mapping with CSV helper the value of one field is null

I have a CSV file in the following format:

Name,Email,ClientCode
Ch S,auseremail@gmail.com,20210603241
HJ BA,buseremail@gmail.com,20210603261

I am using CsvHelper to read the CSV file. When I debug the code in the local environment, data are properly bound to the model.

But when I deploy the code to the production environment, the value of ClientCode is zero or null.

Class I am using:

public class ClientEmail
{
    [Name("Email")]
    public string Email { get; set; }
    [Name("ClientCode")]
    public long ClientCode { get; set; }
    [Name("Name")]
    public string Name { get; set; }
}

public class ClientEmailMap : ClassMap<ClientEmail>
{
    public ClientEmailMap()
    {
        Map(m => m.Name).Name("Name");
        Map(m => m.Email).Name("Email");
        Map(m => m.ClientCode).Name("ClientCode");
    }
}

Code that reads the CSV file and binds it to the model:

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
{
    NewLine = Environment.NewLine,
    Delimiter = ",",
    HeaderValidated = null,
    MissingFieldFound = null,
    IgnoreBlankLines = false,
    HasHeaderRecord = true
};


string path = Path.Combine(_env.WebRootPath, $"csv/{fileName}");

var reader = new StreamReader(Path.Combine(_env.WebRootPath, $"csv/{fileName}"));


using (var csv = new CsvReader(reader, config))
{
        var records = await csv.GetRecordsAsync<ClientEmail>().ToListAsync();
}

Here in the records, the value of ClientCode is always null. So I changed the property type to long from string , but again the value is 0.

The specification for CSV files, RFC 4180 , states that

Each record is located on a separate line, delimited by a line break (CRLF).

Note that CRLF = "\r\n" .

If you are using .NET Core, you could run your code on an operating system where the default newline character sequence is just LF, eg Linux or Mac, so Environment.NewLine would not be the correct NewLine setting, and there would be a CR character on the end of the digits, which could cause parsing them to a number to fail.

The solution is to use NewLine = "\r\n" for CSV files which comply with the standard to make sure your code works everywhere.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM