You are here:   Home
  |  Login

Programmer Newsletter

Minimize

Master Programmer

Minimize

Find articles on computer software, programming, ASP.net, Sql server, databases, C#, websites, Internet, Windows, Outlook macros.

Programming Articles

Minimize
02

Here is a handy way of reading a delimited text file into an Asp.net program.

Rather than reading and parsing the file yourself, you can use the OleDbDataAdapter.

The advantage of this is you can specify an SQL command to pull your data right into a table.

You can then output your results however you want.

You will need these two using statements.

using System.Data;
using System.Data.OleDb;

You can put this method into a class.

//-----------------------------------------------
public class delimited_file_reader_Class {
public DataSet Read_File_Into_Dataset(string fullpath, string file)
{
string sql = "SELECT * FROM " + file; // Read all the data
OleDbConnection connection = new OleDbConnection // Connection
  ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + fullpath + ";"
   + "Extended Properties=\"text;HDR=YES;FMT=Delimited\"");
OleDbDataAdapter ole = new OleDbDataAdapter(sql, connection); // Load the data into the adapter
DataSet dataset = new DataSet(); // To hold the data
ole.Fill(dataset); // Fill the dataset with the data from the adapter
connection.Close(); // Close the connection
connection.Dispose(); // Dispose of the connection
ole.Dispose(); // Get rid of the adapter
return dataset;
}
}
//-----------------------------------------------

In the SQL clause above, for the table name in the FROM clause, use the filename.

In the Connection string for a text file, use the folder containing the file as the Data Source.

In that folder, you need to put a schema.ini file so you can specify the delimiter.

[input.txt]
Format=TabDelimited

[anotherfile.csv]
Format=Delimited(,)

You can call the above method like this and write the results to a file for testing.

delimited_file_reader_Class reader = new delimited_file_reader_Class();
DataSet dataset = reader.Read_File_Into_Dataset("C:\\", "input.txt");
dataset.WriteXml("C:\\output.xml"); // Test to see if the data was loaded

Notes:

  1. You will need to download and install the OleDB Provider from here
    www.microsoft.com/download/en/details.aspx?id=13255
  2. If you get this error message, click the link for a solution.
    The 'Microsoft.Jet.OLEDB.4.0' provider is not registered on the local machine.

Resources:

Connection Strings - www.connectionstrings.com/textfile

DataSet - msdn.microsoft.com/en-us/library/bwy42y0e(v=VS.90).aspx

OleDb Namespace - msdn.microsoft.com/en-us/library/6d9ew87b(v=VS.90).aspx

Posted in: Asp.net

Post Rating

Comments

There are currently no comments, be the first to post one.

Post Comment

Only registered users may post comments.

Reccomend Programmer.bz

Minimize

Share/Bookmark Bookmark and Share