Based on the CsvHelper documentation , we can achieve the desired results in several ways.
1. Ignore spaces in the headers (which, I believe, should easily solve your problem)
In CsvHelper 3 or later PrepareHeaderForMatch use PrepareHeaderForMatch (documented at http://joshclose.imtqy.com/CsvHelper/configuration#headers ) to remove spaces from the headers:
csv.Configuration.PrepareHeaderForMatch = header => Regex.Replace(header, @"\s", string.Empty)
In CsvHelper 2, set the flag IgnoreHeaderWhiteSpace which tells the reader to ignore spaces in the headers when matching columns with properties by name.
reader.Configuration.IgnoreHeaderWhiteSpace = true;
2. Read by hand
We can read each field manually, for example:
var reader = new CsvReader(sr); do { reader.Read(); var record=new DataRecord(); record.TimeOfDay=reader.GetField<string>("Time of Day"); record.ProcessName=reader.GetField<string>("Process Name"); record.PID=reader.GetField<string>("PID"); record.Operation=reader.GetField<string>("Operation"); record.Path=reader.GetField<string>("Path"); record.Result=reader.GetField<string>("Result"); record.Detail=reader.GetField<string>("Detail"); record.ImagePath=reader.GetField<string>("Image Path"); } while (!reader.IsRecordEmpty());
3. Class mapping:
We can manually map between our class properties and headers in a CSV file using name class mapping as follows:
public sealed class DataRecordMap:CsvClassMap<DataRecord> { public DataRecordMap() { Map( m => m.TimeOfDay).Name("Time Of Day"); Map( m => m.ProcessName).Name("Process Name"); Map( m => m.PID).Name("PID"); Map( m => m.Operation).Name("Operation"); Map( m => m.Path).Name("Path"); Map( m => m.Result).Name("Result"); Map( m => m.Detail).Name("Detail"); Map( m => m.ImagePath).Name("Image Path"); } }
Then we must register this using:
reader.Configuration.RegisterClassMap<DataRecordMap>();
source share