Reputation: 6242
I am using CSVHelper to parse the CSV file.
I am having some issues to identify when a null cell value or a cell with some value (ie one or more spaces).
Issue is when the user add just one space in the file in its cell and uploads the file, the CSV helper trims that cell value so that value is passed as "".
Now when the user doesnt add anything(or types) to the cell this is also passed as like "".
So what I want is: - Nulls should not be allowed to be uploaded. - One or more spaces in a cell is allowed.
How can I achieve this using CSVHelper. Below is my sample code:
using (TextReader fileReader = new StreamReader(file.OpenReadStream()))
{
var configuration = new Configuration
{
HasHeaderRecord = parameter.HasHeader,
Delimiter = parameter.Delimiter.ToString(),
Quote = parameter.Quote
};
using (var csv = new CsvReader(fileReader, configuration))
{
for (int rowIndex = 0; await csv.ReadAsync(); rowIndex++)
{
var record = csv.GetRecord<dynamic>() as IDictionary<string, object>;
string[] row = record?.Select(i => i.Value as string).ToArray();
for (int i = 0; i < row.Length; i++)
{
//process rows
}
}
}
}
Below is the csv example:
"1"," ","1"
"2","0"," "
"3","","1"
In the above csv first row has second column with one space which should be allowed Third row has 2nd column with null which should not be allowed.
Anything in my code which is missing or any workaround to handle this?
Thanks
Upvotes: 0
Views: 2204
Reputation: 9074
CsvHelper 15.0.3
With the following code I show spaces where there are spaces and empty where it is empty.
Maybe there is something else going on?
static void Main(string[] args)
{
ProcessRecords();
}
static async void ProcessRecords()
{
using (var reader = new StringReader("\"1\",\" \",\"1\"\n\"2\",\"0\",\" \"\n\"3\",\"\",\"1\""))
{
var configuration = new CsvHelper.Configuration.CsvConfiguration(CultureInfo.InvariantCulture)
{
HasHeaderRecord = false,
Delimiter = ",",
Quote = '"'
};
using (var csv = new CsvReader(reader, configuration))
{
for (int rowIndex = 0; await csv.ReadAsync(); rowIndex++)
{
Console.WriteLine($"Row: {rowIndex}");
var record = csv.GetRecord<dynamic>() as IDictionary<string, object>;
string[] row = record?.Select(i => i.Value as string).ToArray();
for (int i = 0; i < row.Length; i++)
{
if (row[i] == " ")
{
Console.WriteLine("Has a space");
}
if (row[i] == "")
{
Console.WriteLine("Empty value");
}
}
}
Console.ReadKey();
}
}
}
Upvotes: 1