How to Read the Data from CSV File in ASP.NET

Code

  1. <asp:FileUpload ID="fpContacts" runat="server" />  
  2. <asp:Button ID="btnUpload" runat="server" Text="Upload" OnClick="btnUpload_Click" /></p>  
Here we need to add a new folder to the solution, why because, sometimes it will takes the fake file path. it is better to save the file and read data.

In .cs page, write the following code.
  1. protected void btnUpload_Click(object sender, EventArgs e)  
  2. {  
  3.      if (fpContacts.HasFile)  
  4.      {  
  5.          string spath = Server.MapPath("~/upload");  
  6.          string csv_file_path = spath + "\\" + fpContacts.FileName;  
  7.          fpContacts.SaveAs(csv_file_path);  
  8.   
  9.          DataTable csvData = GetDataTableFromCSVFile(csv_file_path);  
  10.      }  
  11.  }  
  12.   
  13.  public DataTable GetDataTableFromCSVFile(string csv_file_path)  
  14.  {  
  15.      DataTable csvData = new DataTable();  
  16.      try  
  17.      {  
  18.          using (TextFieldParser csvReader = new TextFieldParser(csv_file_path))  
  19.          {  
  20.              csvReader.SetDelimiters(new string[] { "," });  
  21.              csvReader.HasFieldsEnclosedInQuotes = true;  
  22.              //read column names  
  23.              string[] colFields = csvReader.ReadFields();  
  24.              foreach (string column in colFields)  
  25.              {  
  26.                  DataColumn datecolumn = new DataColumn(column);  
  27.                  datecolumn.AllowDBNull = true;  
  28.                  csvData.Columns.Add(datecolumn);  
  29.              }  
  30.              while (!csvReader.EndOfData)  
  31.              {  
  32.                  string[] fieldData = csvReader.ReadFields();  
  33.                  ContactEntity CEntity = new ContactEntity();  
  34.                  B2B_BillsData BData = new B2B_BillsData();  
  35.   
  36.                  CEntity.ContactName = fieldData[0];  
  37.                  CEntity.Email = fieldData[1];  
  38.                  CEntity.Mobile = fieldData[2];  
  39.                  CEntity.GroupId = ddlGroup.SelectedIndex;  
  40.                  CEntity.UserId = userid;  
  41.                  if (BData.InsertNewContact(CEntity) == true)  
  42.                  {  
  43.                      lblMsg.ForeColor = Color.Green;  
  44.                      lblMsg.Text = "Contact Saved successfully";  
  45.                  }  
  46.                  csvData.Rows.Add(fieldData);  
  47.              }  
  48.          }  
  49.      }  
  50.      catch (Exception ex)  
  51.      {  
  52.          //MessageBox.Show(ex.Message);  
  53.      }  
  54.      return csvData;  
  55.  }  
Happy coding........