Read csv file and create object from it in CSharp

Description

The following code shows how to read csv file and create object from it.

Example


using System;//  w ww  . ja v  a2s .  c  o  m
using System.IO;
class ReadingFiles {
  public static void Main() 
  {
    String file_name = "Customers.csv";
    StreamReader sr = new StreamReader(file_name);
    String line;
    while ((line = sr.ReadLine())!=null)
    {
      String[] tokens = line.Split(',');
      Customer c = new Customer();
      c.CustomerName = tokens[0];
      c.Street = tokens[1];
      c.City = tokens[2];
      c.AccountNo = tokens[3];        
      Console.WriteLine(c);
    }
    sr.Close();
  }
}
class Customer
{
  public String CustomerName;
  public String Street;
  public String City;
  public String AccountNo;
  public Customer()
  {
  }
  public override String ToString() 
  {
    return CustomerName+"\n"
          +Street+","+City+"\n"
          +"\tAcc #:"+AccountNo+"\n\n";
  }
}




















Home »
  C# Tutorial »
    IO »




File Attribute
File Security
Directory Attribute
Directory Recursive
Binary File
Text Field
Buffered IO
Create Copy Delete Move
CSV
Drive
File System Watcher
Isolated Storage
MemoryStream
Serialize
Zip