I am attempting to import data from a comma delimited csv file into SQL. The csv file has fields in quotes because some of the fields have commas as part of the data. If I split on the comma it is splitting the fields that have commas into 2 fields which I don't want. How do I split it correctly?
CSV file sample:
"LASTNAME","FIRSTNAME","MIDNAME","BUSNAME","GENERAL","SPECIALTY"
"BERRY","JOY","YVONNE ",,"MEDICAL PRACTICE, MD","FAMILY PRACTICE",
"BERRY","JOE"," ",,"IND- LIC HC SERV PRO","NURSE/NURSES AIDE"
Code:
try
{
StreamReader sr = new StreamReader(strFilePath);
string line = sr.ReadLine();
string[] value = line.Split(',');
System.Data.DataTable dt = new System.Data.DataTable();
DataRow row;
foreach (string dc in value)
{
dt.Columns.Add(new DataColumn(dc));
}
while (!sr.EndOfStream)
{
value = (sr.ReadLine()).Split(',');
if (value.Length == dt.Columns.Count)
{
row = dt.NewRow();
row.ItemArray = value;
dt.Rows.Add(row);
}
}
SqlBulkCopy bc = new SqlBulkCopy(connsql.ConnectionString, SqlBulkCopyOptions.TableLock);
bc.DestinationTableName = tablename;
bc.BatchSize = dt.Rows.Count;
bc.WriteToServer(dt);
bc.Close();
}
catch (Exception ex)
{
//MessageBox.Show("Error importing Staff Summary: " + ex.Message);
connsql.Close();
}