2

I want insert data from CSV file to SQL table. Here is my code I don't know how to go further

var readcsv = File.ReadAllText(filepath);
string[] csvfilerecord = readcsv.Split('\n');

foreach (var row in csvfilerecord)
{
  if (!string.IsNullOrEmpty(row))
  {
    foreach (var cell in row.Split(','))
    {
      var cards = new Cards
      {
        //What to do here to assign data to each column 
      };
    }
  }
}

here is my csv file data

12345,cvv,18-april,name,country,address,state,city,dob,zipcode,phone,email,10
12345,cvv,18-april,name,country,address,state,city,dob,zipcode,phone,email,10

class Definition

        public string nummber { get; set; }
    public string cvv { get; set; }
    public string expDate { get; set; }
    public string name { get; set; }
    public string country { get; set; }
    public string address { get; set; }
    public string state { get; set; }
    public string dob { get; set; }
9
  • What's the definition of Cards class? Commented Jun 29, 2016 at 10:00
  • 3
    Use tools like github.com/JoshClose/CsvHelper - you can map row directly to proxy class. Commented Jun 29, 2016 at 10:00
  • its an entity i want to insert record in it Commented Jun 29, 2016 at 10:02
  • Yea.. Can you show its definition? Commented Jun 29, 2016 at 10:02
  • it has different columns like number cvv , dob , name , country etc Commented Jun 29, 2016 at 10:03

2 Answers 2

2

You need to know which column of the CSV maps to which property. With this information you can map values into properties.

Assuming you have a dictionary of indexes columnMap you can use

var cells = row.Split(',');
var cards = new Cards {
  prop = cells[columnMap["prop"]],
  nextProp = cells[columnMap["nextProp"]],
  …
}

Note I do not iterate over the separate values from one row in the CSV.

Also note you need a proper CSV parser to handle the escaping/quoting necessary for when values contain commas or quotes.

Sign up to request clarification or add additional context in comments.

Comments

1
var readcsv = File.ReadAllText(filepath);
string[] csvfilerecord = readcsv.Split('\n');

foreach (var row in csvfilerecord)
{
  if (!string.IsNullOrEmpty(row))
  {
    var cells = row.Split(','))
    var card = new Cards
      {
         number = cells[0], // number is in first cell
         cvv = cells[1],   // cvv is in second cell
         // ...
      };
  }
}

1 Comment

In order to tackle newline problem in different OS, I suggest using File.ReadAllLines(filepath), instead of .Split('\n') method.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.