Solved

C#: Import data from csv into datatable

Posted on 2008-10-06
6
10,809 Views
Last Modified: 2013-12-17
Can some one help me import data from a comma separated value file into a datatable?
0
Comment
Question by:karakav
6 Comments
 
LVL 55

Expert Comment

by:Jaime Olivares
Comment Utility
0
 
LVL 13

Expert Comment

by:SameerJagdale
Comment Utility
0
 
LVL 16

Expert Comment

by:Gyanendra Singh
Comment Utility
please find sample code
//Namespace reference

using System.IO;

using System.Data;

 

#region BuildDataSet

/// <summary>

/// method to read a text file into a DataSet

/// </summary>

/// <param name="file">file to read from</param>

/// <param name="tableName">name of the DataTable we want to add</param>

/// <param name="delimeter">delimiter to split on</param>

/// <returns>a populated DataSet</returns>

public DataSet BuildDataSet(string file,string tableName,string delimeter)

{

    //create our DataSet

    DataSet domains = new DataSet();

    //add our table

    domains.Tables.Add(tableName);

    try

    {

        //first make sure the file exists

        if (File.Exists(file))

        {

            //create a StreamReader and open our text file

            StreamReader reader = new StreamReader(file);

            //read the first line in and split it into columns

            string[] columns = reader.ReadLine().Split(delimeter.ToCharArray());

            //now add our columns (we will check to make sure the column doesnt exist before adding it)

            foreach (string col in columns)

            {

                //variable to determine if a column has been added

                bool added = false;

                string next = "";

                //our counter

                int i = 0;

                while (!(added))

                {

                    string columnName = col;

                    //now check to see if the column already exists in our DataTable

                    if (!(domains.Tables[tableName].Columns.Contains(columnName)))

                    {

                        //since its not in our DataSet we will add it

                        domains.Tables[tableName].Columns.Add(columnName, typeof(string));

                        added = true;

                    }

                    else

                    {

                        //we didnt add the column so increment out counter

                        i++;

                    }

                }

            }

            //now we need to read the rest of the text file

            string data = reader.ReadToEnd();

            //now we will split the file on the carriage return/line feed

            //and toss it into a string array

            string[] rows = data.Split("\r".ToCharArray());

            //now we will add the rows to our DataTable

            foreach (string r in rows)

            {

                string[] items = r.Split(delimeter.ToCharArray());

                //split the row at the delimiter

                domains.Tables[tableName].Rows.Add(items);

            }

        }

        else

        {

            throw new FileNotFoundException("The file " + file + " could not be found");

        }

        

    }

    catch (FileNotFoundException ex)

    {

        _message = ex.Message;

        return null;

    }

    catch (Exception ex)

    {

        _message = ex.Message;

        return null;

    }

    

    //now return the DataSet

    return domains;

}

#endregion

 

 

//Sample usage

 

//for a Windows application

DataSet data = BuildDataSet("C:\MyFile.txt","MyTable",",");

 

//For an ASP.Net application

DataSet data = BuildDataSet(Server.MapPath("MyFile.txt"),"MyTable",",");

Open in new window

0
6 Surprising Benefits of Threat Intelligence

All sorts of threat intelligence is available on the web. Intelligence you can learn from, and use to anticipate and prepare for future attacks.

 
LVL 4

Author Comment

by:karakav
Comment Utility
If possible I would like a solution that takes advantage of OleDb.
0
 
LVL 13

Accepted Solution

by:
SameerJagdale earned 500 total points
Comment Utility
0
 
LVL 4

Author Closing Comment

by:karakav
Comment Utility
Thanks.
0

Featured Post

Highfive Gives IT Their Time Back

Highfive is so simple that setting up every meeting room takes just minutes and every employee will be able to start or join a call from any room with ease. Never be called into a meeting just to get it started again. This is how video conferencing should work!

Join & Write a Comment

Wouldn’t it be nice if you could test whether an element is contained in an array by using a Contains method just like the one available on List objects? Wouldn’t it be good if you could write code like this? (CODE) In .NET 3.5, this is possible…
It was really hard time for me to get the understanding of Delegates in C#. I went through many websites and articles but I found them very clumsy. After going through those sites, I noted down the points in a easy way so here I am sharing that unde…
Sending a Secure fax is easy with eFax Corporate (http://www.enterprise.efax.com). First, Just open a new email message.  In the To field, type your recipient's fax number @efaxsend.com. You can even send a secure international fax — just include t…
Access reports are powerful and flexible. Learn how to create a query and then a grouped report using the wizard. Modify the report design after the wizard is done to make it look better. There will be another video to explain how to put the final p…

772 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question

Need Help in Real-Time?

Connect with top rated Experts

13 Experts available now in Live!

Get 1:1 Help Now