2

What's the best way to import a small csv file into SQL Server using an ASP.NET form with C#? I know there are many ways to do this, but I'm wondering which classes would be best to read the file and how to insert into the database. Do I read the file into a DataTable and then use the SqlBulkCopy class, or just insert the data using ADO.NET? Not sure which way is best. I'm after the simplest solution and am not concerned about scalability or performance as the csv files are tiny.

Using ASP.NET 4.0, C# 4.0 and SQL Server 2008 R2.

1 Answer 1

3

The DataTable and the SqlBulkCopy classes will do just fine and that is the way I would prefer to do it, in order to prevent that someday these tiny CSV files become larger, your program will be ready for it, as ADO.NET might add some overhead by treating a single row at a time.

EDIT #1

What's the best way to get from csv file to datatable?

The CSV file format is nothing more than a text file. As such, you might want to read it using the File.ReadAllLines Method (String), which will return a string[]. Then, you may add to your DataTable using the DataRow class or your prefered way.

Consider adding your columns when defining your DataTable so that it knows its structure when adding rows.

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

2 Comments

Thanks - what's the best way to get from csv file to datatable?
This sort of reply would be a perfect time to mention VB.Nets DelimitedFileParser - something which is hugely overlooked because its not known about, which often means people go outside of the core .Net framework to handle csv files. You can use it in C# very easily.

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.