Link to home
Start Free TrialLog in
Avatar of Hojoformo
Hojoformo

asked on

Reading a text file into a DataTable

What is the easiest way to LOAD a text file into a DataTable?  I have a windows form application that read in a comma delimited text file.  I want to load this text file into a datatable so what is the easiest way to do this.

Here is how I am reading the text file now.
 try
     {
          using (StreamReader sr = new StreamReader(strFileName.ToString()))
           {
              while ((line = sr.ReadLine()) != null)
                    {
                            Values = line.Split(Convert.ToChar(FileMapWindow.SelectedDelimiter));

I want to read this file into a DataTable dt = new DataTable() instead.
ASKER CERTIFIED SOLUTION
Avatar of TheMozz
TheMozz
Flag of United States of America image

Link to home
membership
This solution is only available to members.
To access this solution, you must be a member of Experts Exchange.
Start Free Trial
Avatar of Dmitry G
I believe there are LOT of references around how to import a file into a grid.

Just have a look:
http://www.netomatix.com/development/ImportCSVIntoGrid.aspx
http://forums.devx.com/showthread.php?t=148498

The second link is VB.Net code so you may want to convert it to C# -see converted.

I used the http://www.developerfusion.com/tools/convert/vb-to-csharp/ converter and didn't test the code.
private void Button3_Click(System.Object sender, System.EventArgs e)
{
	if (OpenFileDialog1.ShowDialog(this) == DialogResult.OK) {
		FileInfo fi = new FileInfo(OpenFileDialog1.FileName);
		string sConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;Extended Properties=Text;Data Source=" + fi.DirectoryName;
		OleDbConnection objConn = new OleDbConnection(sConnectionString);
		objConn.Open();
		OleDbCommand objCmdSelect = new OleDbCommand("SELECT * FROM " + fi.Name, objConn);
		OleDbDataAdapter objAdapter1 = new OleDbDataAdapter();
		objAdapter1.SelectCommand = objCmdSelect;
		DataSet objDataset1 = new DataSet();
		objAdapter1.Fill(objDataset1, "test");
		DataGrid1.DataSource = objDataset1.Tables[0].DefaultView;
		objConn.Close();
	}

}

Open in new window

Avatar of nipunu
nipunu

//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",",");


// Convert DataSet to DataTable by getting DataTable at first zero-based index of DataTableCollection
DataTable myDataTable = data.Tables[0];