Search code examples
c#csvparsingcsvhelper

CsvFile Header Row does not match output, ex(Header = Tol +, Console output = Tol_plus) C#,csvHelper


Hello I am parsing a csvFile using csvHelper and Ive come to a roadbloack. One of the headers in the header is "Tol +".I was not able to put it as a variable name, and thus I mapped it as "Tol_plus" using the automapping class. However, when I output the file, I receive:

(Console output of Header Row below)
Measurement,Nominal,Tol_plus

What I want:

(How Header Row  actually looks below)
Measurement,Nominal,Tol +

Here is the code I have so far:

public class Foo
        {

            public string Measurement { get; set; }//read as string
            public string Nominal { get; set; } //reads in data from here
            public string Tol_plus { get; set; }//reads in data from here 
        }

public sealed class FooMap : ClassMap<Foo>
        {
            public FooMap()
            {
                Map(m => m.Measurement).Name("Measurement");//maps the variables from the class above to things in quotes
                Map(m => m.Nominal).Name("Nominal");

                Map(m => m.Tol_plus).Name("Tol +");
            }
        }
//main method
void main()
 var textwriter = Console.Out;
             using (var csvWriter = new CsvWriter(textwriter, CultureInfo.InvariantCulture))
             using (var reader = new StreamReader(@"path.csv"))
             using (var csv = new CsvReader(reader, CultureInfo.InvariantCulture))
             {
                csv.Read();
                csv.ReadHeader();
                csv.Configuration.RegisterClassMap<FooMap>();//necessary for mapping 
                var records = csv.GetRecords<Foo>();
                csvWriter.WriteRecords(records);
              }
//The output here gives me: 
Measurement,Nominal,Tol_plus

For this, I tried passing in a string literal to into Tol_plus but that didnt work, would there be a way to map it so it prints out "Tol +" instead of "Tol_plus"?


Solution

  • Based on Edney's comment:

    public class Foo
            {
    
                public string Measurement { get; set; }//read as string
                public string Nominal { get; set; } //reads in data from here
    
                [CsvHelper.Configuration.Attributes.Name("Tol +")]
                public string Tol_plus { get; set; }//reads in data from here 
            }
    

    By adding the line:

    [CsvHelper.Configuration.Attributes.Name("Tol +")]
    

    It changes the name to "Tol +" during output.