The below code will do so
public static DataTable ConvertPipedCSVToDataTable(string source)
{
DataTable dt = new DataTable();
try
{
using (var stream = new MemoryStream())
{
var input = source;
var bytes = System.Text.Encoding.Default.GetBytes(input);
stream.Write(bytes, 0, bytes.Length);
stream.Seek(0, SeekOrigin.Begin);
using (var csvReader = new TextFieldParser(stream))
{
csvReader.SetDelimiters(new string[] { "|" });
csvReader.HasFieldsEnclosedInQuotes = true;
string[] colFields = csvReader.ReadFields();
foreach (string column in colFields)
{
DataColumn datecolumn = new DataColumn(column);
datecolumn.AllowDBNull = true;
dt.Columns.Add(datecolumn);
}
while (!csvReader.EndOfData)
{
string[] fieldData = csvReader.ReadFields();
//Making empty value as null
for (int i = 0; i < fieldData.Length; i++)
{
if (fieldData[i] == "")
{
fieldData[i] = null;
}
}
dt.Rows.Add(fieldData);
}
return dt;
}
}
}
catch (Exception ex)
{
throw ex;
}
}