简体   繁体   中英

Reading CSV Files using Fast CsvReader without quotes around fields

I'm having some issues using Lumenworks Fast CsvReader . Using the code:

using (CsvReader csv = new CsvReader(new StreamReader(Server.MapPath(fileName)), true))
{
     csv.ParseError += csv_ParseError;

     while (csv.ReadNextRecord())
     {
          var importItem = new ProductImportItem(csv);
          if (!ProductsDALC.SearchByPartProductCode(importItem.ProductCode).Any())
          {
              if (!SaveProduct(importItem))
              {
                  this.ParseErrors.Add(string.Format("Failed to add product-{0}", importItem.ProductCode));
              }
          }
     }
}

The code works fine when the CSV file is formatted using double quotes either side of the fields/column values eg:

"product_code", "product_name", "item_description", "sku", "postage_level_required", "cost_price", "retail_price_inc_vat"

However, if the columns look like this:

product_code,product_name,item_description,sku,postage_level_required,cost_price,retail_price_inc_vat

Then the code behaves as if there is no data, that is to say, it won't enter into the while loop and enumerating the result set in the debugger will show that it yields no results.

This would be fine if I had absolute control over the data in/out. However, all I can do is provide the user with a template which contains the fields and hope that they wrap the data in quotes. This isn't an acceptable approach.

Is there a way to get the reader to parse data even if it isn't wrapped in quotes?

I'm aware of the TextFieldParser class built into .Net which handles this fine but since we're using CsvReader elsewhere in the projec it would be good to remain consistent.

You have to provide the information that the fields aren't quoted in the constructor by using the unicode "null" character :

Char quotingCharacter = '\0';  // means none
Char escapeCharacter  = '\0';
Char commentCharacter = '\0';
Char delimiter = ',';
bool hasHeader = true;
using (var csv = new CsvReader(reader, hasHeader, delimiter, quotingCharacter, escapeCharacter, commentCharacter, ValueTrimmingOptions.All))
{
    // ...
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM