Download Code

Introduction

This article explains how to display a remote CSV file and bind it to a GridView without downloading or storing it temporaraily. Also, I have included how to read a local CSV and bind it to a GridView.

Using the code

We have to follow just a few steps to achieve it. First, make a web request to the URL of the CSV file. After retrieving the response into a StreamReader, retrieve the first row from the StreamReader and make a table with the column specified in the first row of the CSV file. Retrieve the data row by row and adds the rows to the table. Bind the GridView after adding all the rows to the DataTable. That is it. Here is the code:

//to display remote csv file
protected void btnDispRemote_Click(object sender, EventArgs e)
{
    try
    {
        System.Net.HttpWebRequest WebRequest;
        string URL = txtRemote.Text.Trim(); //URL of the remote csv
        Uri CSVUri = new Uri(URL);
        WebRequest = (System.Net.HttpWebRequest)
                      System.Net.HttpWebRequest.Create(CSVUri);
        if ((WebRequest.GetResponse().ContentLength > 0))
        {
            System.IO.StreamReader strReader =
              new System.IO.StreamReader(
              WebRequest.GetResponse().GetResponseStream());
           
            //create datatable with column names
            CreateCSVTable(strReader.ReadLine());
            String SingleLine;
            while ((SingleLine = strReader.ReadLine()) != null)
            {
                AddRowCSVTable(SingleLine);
                //adding rows to datatable
            }
            grdList.DataSource = CSVTable;
            grdList.DataBind();
            if (strReader != null) strReader.Close();
        }
    }
    catch (System.Net.WebException ex)
    {
        lblMsg.Text = "File does not exist.";
    }
}

We have two separate methods for creating the DataTable from the CSV data and to add row wise data to the DataTable. These two methods are as follows:

//to create the data table with columns
public void CreateCSVTable(string TableColumnList)
{
    CSVTable = new DataTable("CSVTable");
    DataColumn myDataColumn;
    string[] ColumnName = TableColumnList.Split(',');
    for (int i = 0; i < ColumnName.Length - 1; i++)
    {
        myDataColumn = new DataColumn();
        myDataColumn.DataType =
           Type.GetType("System.String");
        myDataColumn.ColumnName = ColumnName[i];
        CSVTable.Columns.Add(myDataColumn);
    }
}
//to add the rows to datatable
public void AddRowCSVTable(string RowValueList)
{
    string[] RowValue = RowValueList.Split(',');
    DataRow myDataRow;
    myDataRow = CSVTable.NewRow();
    for (int i = 0; i < RowValue.Length - 1; i++)
    {
        myDataRow[i] = RowValue[i];
    }
    CSVTable.Rows.Add(myDataRow);
}

To display a CSV file residing on the system or an application folder, we can easily use simple steps to create an OLEDB connection, command, and adaptor. Sample code is shown below:

//to display local csv file
protected void btnDispLoc_Click(object sender, EventArgs e)
{
    string filename=fl.PostedFile.FileName.ToString();
    FileInfo file = new FileInfo(filename);
    string ConnectionString = "Provider=Microsoft.Jet.OLEDB.4.0;" +
           "Data Source=\"" + file.DirectoryName +
           "\";Extended Properties='text;HDR=Yes;FMT=Delimited(,)';";
    OleDbConnection con = new OleDbConnection(ConnectionString);
    OleDbCommand cmd = new OleDbCommand(string.Format(
      "SELECT * FROM [" + file.Name + "]", file.Name), con);
    try
    {
        con.Open();
        OleDbDataAdapter oda = new OleDbDataAdapter(cmd);
        DataTable dt = new DataTable("CSVTable");
        oda.Fill(dt);
        grdList.DataSource = dt;
        grdList.DataBind();
    }
    catch (Exception ee)
    {
        lblMsg.Text = ee.Message;
    }
}
Copyrights 2018, www.expertsupdates.com