Mark Brown

Hmm...

<November 2008>
SuMoTuWeThFrSa
2627282930311
2345678
9101112131415
16171819202122
23242526272829
30123456


Navigation

Work Links

Subscriptions

Post Categories

Article Categories



Wednesday, July 30, 2003 - Posts

Parsing CSV files

Ed Kaim points out a method to import a CSV file into a DataSet. I'm probably one of those fellows that found his site while searching Google. I went about the procedure a little bit differently. Here's what I put together:

 

static DataSet ReadCSV(string file)
{
    if (! File.Exists(file) )
        return null;
    DataSet ds = new DataSet();
    OleDbConnection conn = null;
    string FileConnection = "Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + 
        @Path.GetDirectoryName(file) + ";" + @"Extended Properties=""Text;HDR=YES;""";
    try
    {
        try
        {
            conn = new OleDbConnection();
            conn.ConnectionString = FileConnection;
            conn.Open();
        }
        catch
        {
            Console.WriteLine("Database connection can't be established");
            return null;
        }
        string sql = String.Format("SELECT * FROM {0}",Path.GetFileName(file));
        OleDbDataAdapter oda = new OleDbDataAdapter(sql, conn); 
        oda.SelectCommand.ExecuteNonQuery();
        oda.Fill(ds, "TableName");
    }
    catch (Exception e)
    {
        Console.WriteLine(e.Message);
        return null;
    }
    finally
    {
        if(conn != null)
            conn.Dispose();
    }
    return ds;
}

posted Wednesday, July 30, 2003 5:28 PM by MarkBrown with 0 Comments




Powered by Dot Net Junkies, by Telligent Systems