2

I've written a handy little class to generate CSV files from various data sources. For example, I can pass in a DataTable or a collection of IEnumerable objects (each effectively representing a 'row') and it will faithfully escape and delimit the file as needed. It seems to work quite well but I'm trying to think of the best way to tackle the final piece.

I want to allow the ability to set default formatters for each Type that gets outputted to the CSV. So for example, I'd like to be able to specify a Locale-specific date format to use for all DateTimes. Or alternately maybe one of your fields is a decimal number and you want it to be formatted as currency in the output to the CSV. (so basically the ability to define a global formatter for a given datatype, and/or a specific formatter for a specific column in the data (i.e. just the 'price' field formatted to currency))

I've dug around the .NET framework and I haven't been able to find anything like this. IS this just something I need to roll on my own? And if so are there any useful classes I might look at in this quest?

thanks!

Erik Philips
  • 53,428
  • 11
  • 128
  • 150
snappymcsnap
  • 2,050
  • 2
  • 29
  • 53

1 Answers1

3

IS this just something I need to roll on my own?

Yes.

are there any useful classes I might look at in this quest?

Not a class, but an interface - IFormatProvider.

You will need to implement it for all the types you want to format and pass in your implementation to the different formatting functions.

Take a look at this code project example for implementation and this SO question and answers for some caveats.

You may also want to take a look at the IFormattable interface as it is specifically about formatting objects into string representations.

Community
  • 1
  • 1
Oded
  • 489,969
  • 99
  • 883
  • 1,009
  • excellent, thanks for the help...it looks like the framework actually has the two most common implmentations for IFormatProvider in System.Globalization.DateTimeFormatInfo and System.Globalization.NumberFormatInfo, I suspect that will help quite a bit with this effort – snappymcsnap Apr 26 '12 at 19:22