Read comma separated value into DataSet : CSV « Database ADO.net « C# / C Sharp

Home
C# / C Sharp
1.2D Graphics
2.Class Interface
3.Collections Data Structure
4.Components
5.Data Types
6.Database ADO.net
7.Design Patterns
8.Development Class
9.Event
10.File Stream
11.Generics
12.GUI Windows Form
13.Language Basics
14.LINQ
15.Network
16.Office
17.Reflection
18.Regular Expressions
19.Security
20.Services Event
21.Thread
22.Web Services
23.Windows
24.Windows Presentation Foundation
25.XML
26.XML LINQ
C# / C Sharp by API
C# / CSharp Tutorial
C# / CSharp Open Source
C# / C Sharp » Database ADO.net » CSVScreenshots 
Read comma separated value into DataSet
Read comma separated value into DataSet


using System;
using System.Data;
using System.IO;

class Class1{
    static void Main(string[] args){
         DataSet myDataSet = GetData();
         foreach (DataColumn c in myDataSet.Tables["TheData"].Columns){
            Console.Write("{0,-20}",c.ColumnName);
         }
         Console.WriteLine();

         foreach (DataRow r in myDataSet.Tables["TheData"].Rows)
         {
            foreach (DataColumn c in myDataSet.Tables["TheData"].Columns)
            {
               Console.Write("{0,-20}",r[c]);
            }
            Console.WriteLine();
         }
    }

    private static DataSet GetData(){
         string strLine;
         string[] strArray;
         char[] charArray = new char[] {','};
         DataSet ds = new DataSet();
         DataTable dt = ds.Tables.Add("TheData");
         FileStream aFile = new FileStream("csv.txt",FileMode.Open);
         StreamReader sr = new StreamReader(aFile);

         strLine = sr.ReadLine();

         strArray = strLine.Split(charArray);
         
         for(int x=0;x<=strArray.GetUpperBound(0);x++) {
            dt.Columns.Add(strArray[x].Trim());
         }
         
         strLine = sr.ReadLine();
         while(strLine != null) {
            strArray = strLine.Split(charArray);
            DataRow dr = dt.NewRow();
            for(int i=0;i<=strArray.GetUpperBound(0);i++) {
               dr[i= strArray[i].Trim();
            }
            dt.Rows.Add(dr);
            strLine = sr.ReadLine();
         }
         sr.Close();
         return ds;
    }
}

// File: csv.txt
/*

1,2,3,4
5,6,7,8
*/


           
       
Related examples in the same category
1.This example will read a csv file into a dataset and save it back when you press button 1
www.java2java.com | Contact Us
Copyright 2009 - 12 Demo Source and Support. All rights reserved.
All other trademarks are property of their respective owners.