Overriding default quoted empty string handling for csv files

27 views
Skip to first unread message

shriop

unread,
Oct 2, 2007, 11:11:56 AM10/2/07
to CSVChat
I was asked an interesting question, so I figured the answer might be
helpful to other people. There is a somewhat loose standard in the csv
world that there's a difference between a field that has no actual
data in the csv file, so it's just back to back delimiters, and a
field that is quoted/text qualified, but has no data inside the
quotes. Empty quoted fields normally denote an empty string as opposed
to a null value for that field if the datatype for that field is a
text datatype. This logic is actually built into CsvDataReader and
isn't necessarily straightforward to override. Some companies, like
the company of the person who asked the question, have a standard of
never saving empty strings in the database and instead always saving
nulls, which would require the default behavior to be overriden. The
code below will set any field value to null if it is currently an
empty string for all fields in a record on a per record basis.

static void Main(string[] args)
{
using (CsvDataReader reader = new CsvDataReader("quotedvalues.csv"))
{
reader.ReadRecord += new
DataStreams.Common.DataReaderBase.ReadRecordEventHandler(reader_ReadRecord);
...
}
}

static void
reader_ReadRecord(DataStreams.Common.DataReaderBase.ReadRecordEventArgs
e)
{
// this overrides default behavior of quoted empty cells being
treated as
// empty strings to instead consider them as actual null values
for (int i = 0; i < e.Values.Count; i++)
{
if (e.Values[i] != null && e.Values[i].Length = 0)
{
e.Values[i] = null;
}
}
}

Bruce Dunwiddie

Reply all
Reply to author
Forward
0 new messages