Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Reading a CSV file in .NET?

Tags:

browser

c#

.net

csv

How do I read a CSV file using C#?

like image 712
Janmejay Avatar asked Sep 10 '09 12:09

Janmejay


People also ask

What is CSV file in C#?

CSV (Comma Separated Values) is a very popular import and export data format used in spreadsheets and databases. Each line in a CSV file is a data record. Each record consists of one or more fields, separated by commas.


2 Answers

A choice, without using third-party components, is to use the class Microsoft.VisualBasic.FileIO.TextFieldParser (http://msdn.microsoft.com/en-us/library/microsoft.visualbasic.fileio.textfieldparser.aspx) . It provides all the functions for parsing CSV. It is sufficient to import the Microsoft.VisualBasic assembly.

var parser = new Microsoft.VisualBasic.FileIO.TextFieldParser(file); parser.TextFieldType = Microsoft.VisualBasic.FileIO.FieldType.Delimited; parser.SetDelimiters(new string[] { ";" });  while (!parser.EndOfData) {     string[] row = parser.ReadFields();     /* do something */ } 
like image 58
wahrheit Avatar answered Oct 06 '22 01:10

wahrheit


You can use the Microsoft.VisualBasic.FileIO.TextFieldParser class in C#:

using System; using System.Data; using Microsoft.VisualBasic.FileIO;  static void Main() {     string csv_file_path = @"C:\Users\Administrator\Desktop\test.csv";      DataTable csvData = GetDataTableFromCSVFile(csv_file_path);      Console.WriteLine("Rows count:" + csvData.Rows.Count);         Console.ReadLine(); }  private static DataTable GetDataTableFromCSVFile(string csv_file_path) {     DataTable csvData = new DataTable();      try     {         using(TextFieldParser csvReader = new TextFieldParser(csv_file_path))         {             csvReader.SetDelimiters(new string[] { "," });             csvReader.HasFieldsEnclosedInQuotes = true;             string[] colFields = csvReader.ReadFields();              foreach (string column in colFields)             {                 DataColumn datecolumn = new DataColumn(column);                 datecolumn.AllowDBNull = true;                 csvData.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;                     }                 }                  csvData.Rows.Add(fieldData);              }          }      }      catch (Exception ex)      {      }       return csvData; } 
like image 34
kombsh Avatar answered Oct 06 '22 00:10

kombsh