0

I am using the excellent CsvHelper libary. Now I need to explicitly add some leading and trailing spaces to a field. I do this using:

private const string Space = " ";
//....
Map(x => x.Bandwidth).Index(++indexCounter).ConvertUsing(item => Space + item + Space).Name("Bandwidth");

This works, as long as I do not choose to generally trim using

// Default value
csv.Configuration.TrimFields = true;

as described in the CsvHelper docs. But how can I generally use trimming, excpet for a specific field? I am using version 2.5.0 at the moment.

Is there a way to omit trimming for one field only?

Edit:

I just found out that my approach using ConvertUsing is completely broken: See CsvHelper ConvertUsing not changing output I'm going to either delete or update this question later.

Marcel
  • 15,039
  • 20
  • 92
  • 150

2 Answers2

0

I got this completely wrong, and the mapping with ConvertUsing did not work in the first place, and has nothing to do with the option TrimFields = true.

I got it to work with an explicit converter class:

public class CsvExportStringSpacingConverter : DefaultTypeConverter {
    private const string Space = " ";

    public override string ConvertToString(TypeConverterOptions options, object value) {
        return Space + value + Space;
    }
}

Then I changed my mapping to

Map(x => x.Bandwidth)
    .Index(++indexCounter)
    .TypeConverter<CsvExportStringSpacingConverter>)
    .Name(CsvExportColumnName.Bandwidth);

This solution now works, adding leading and trailing spaces for this field, regardless of the trim option. Strangely though, it also automatically adds quotes to this field output, even with this option not enabled. It does not hurt however, Microsoft Excel shows the field content as expected, without quotes, but with the spaces.

Marcel
  • 15,039
  • 20
  • 92
  • 150
0

Using the CsvConfiguration, you can change the CSV file configuration. To trim the fields, please add TrimOptions.Trim.

I am using CSVHelper V28.1

var config = new CsvConfiguration(CultureInfo.InvariantCulture)
                {
                    ShouldQuote = (field) => false,
                };
    config.TrimOptions = TrimOptions.Trim; // Trim the fields
    using (StreamWriter _streamWriter = new StreamWriter(fileNamePath))
                {
                    using (var _csvWriter = new CsvWriter(_streamWriter, config))
                    {
                        await _csvWriter.WriteRecordsAsync(models);
                    }
                }
Jai
  • 1
  • 1