DotNet Friends

August 27, 2008

Upload CSV File And Read Using ASP.net

steps :

1) Create Simple Web Application Using (ASP.Net with C#).

2) Create Class CSVReader (CSVReader.cs)

   1: using System;
   2: using System.Data;
   3: using System.Configuration;
   4: using System.Web;
   5: using System.Web.Security;
   6: using System.Web.UI;
   7: using System.Web.UI.WebControls;
   8: using System.Web.UI.WebControls.WebParts;
   9: using System.Web.UI.HtmlControls;
  10: using System.IO;
  11: using System.Text;
  12: using System.Collections;
  13:  
  14: public class CSVReader
  15: {
  16:     //
  17:     private Stream objStream;
  18:     private StreamReader objReader;
  19:  
  20:     //add name space System.IO.Stream
  21:     public CSVReader(Stream filestream) : this(filestream, null) { }
  22:  
  23:     public CSVReader(Stream filestream, Encoding enc)
  24:     {
  25:         this.objStream = filestream;
  26:         //check the Pass Stream whether it is readable or not
  27:         if (!filestream.CanRead)
  28:         {
  29:             return;
  30:         }
  31:         objReader = (enc != null) ? new StreamReader(filestream, enc) : new StreamReader(filestream);
  32:     }
  33:     //parse the Line
  34:     public string[] GetCSVLine()
  35:     {
  36:         string data = objReader.ReadLine();
  37:         if (data == null) return null;
  38:         if (data.Length == 0) return new string[0];
  39:         //System.Collection.Generic
  40:         ArrayList result = new ArrayList();
  41:         //parsing CSV Data
  42:         ParseCSVData(result, data);
  43:         return (string[])result.ToArray(typeof(string));
  44:     }
  45:  
  46:     private void ParseCSVData(ArrayList result, string data)
  47:     {
  48:         int position = -1;
  49:         while (position < data.Length)
  50:             result.Add(ParseCSVField(ref data, ref position));
  51:     }
  52:  
  53:     private string ParseCSVField(ref string data, ref int StartSeperatorPos)
  54:     {
  55:         if (StartSeperatorPos == data.Length - 1)
  56:         {
  57:             StartSeperatorPos++;
  58:             return "";
  59:         }
  60:  
  61:         int fromPos = StartSeperatorPos + 1;
  62:         if (data[fromPos] == '"')
  63:         {
  64:             int nextSingleQuote = GetSingleQuote(data, fromPos + 1);
  65:             int lines = 1;
  66:             while (nextSingleQuote == -1)
  67:             {
  68:                 data = data + "\n" + objReader.ReadLine();
  69:                 nextSingleQuote = GetSingleQuote(data, fromPos + 1);
  70:                 lines++;
  71:                 if (lines > 20)
  72:                     throw new Exception("lines overflow: " + data);
  73:             }
  74:             StartSeperatorPos = nextSingleQuote + 1;
  75:             string tempString = data.Substring(fromPos + 1, nextSingleQuote - fromPos - 1);
  76:             tempString = tempString.Replace("'", "''");
  77:             return tempString.Replace("\"\"", "\"");
  78:         }
  79:  
  80:         int nextComma = data.IndexOf(',', fromPos);
  81:         if (nextComma == -1)
  82:         {
  83:             StartSeperatorPos = data.Length;
  84:             return data.Substring(fromPos);
  85:         }
  86:         else
  87:         {
  88:             StartSeperatorPos = nextComma;
  89:             return data.Substring(fromPos, nextComma - fromPos);
  90:         }
  91:     }
  92:  
  93:     private int GetSingleQuote(string data, int SFrom)
  94:     {
  95:         int i = SFrom - 1;
  96:         while (++i < data.Length)
  97:             if (data[i] == '"')
  98:             {
  99:                 if (i < data.Length - 1 && data[i + 1] == '"')
 100:                 {
 101:                     i++;
 102:                     continue;
 103:                 }
 104:                 else
 105:                     return i;
 106:             }
 107:         return -1;
 108:     }
 109: }
 110:  

3) put below control in to the aspx page.

<table>
 <tr>
  <td>
   <asp:FileUpload ID="FileUpload1" runat="server" />
  </td>
  <td>
   <asp:Button ID="Button1" runat="server" OnClick="Button1_Click" Text="Upload CSV" />
  </td>
 </tr>
 <tr>
   <td colspan="2">
    <asp:Label ID="lblMsg" Text="Please Select Proper File" runat="server" BorderColor="White"
         Font-Bold="True" ForeColor="Red" Visible="false"></asp:Label>
   </td>
 </tr>
 <tr>
   <td>
    <asp:GridView ID="gv" runat="server"></asp:GridView>
   </td>
 </tr>
</table>

4) In Code Behind File Put Below Code.

   1: protected void Button1_Click(object sender, EventArgs e)
   2:    {
   3:        if (FileUpload1.PostedFile.FileName == string.Empty)
   4:        {
   5:            lblMsg.Visible = true;
   6:            return;
   7:        }
   8:        else
   9:        { 
  10:            //save the file 
  11:            //restrict user to upload other file extenstion
  12:            string[] FileExt = FileUpload1.FileName.Split('.');
  13:            string FileEx = FileExt[FileExt.Length - 1];
  14:            if (FileEx.ToLower() == "csv")
  15:            {
  16:                FileUpload1.SaveAs(Server.MapPath("CSVLoad//" + FileUpload1.FileName));
  17:            }
  18:            else
  19:            {
  20:                lblMsg.Visible = true;
  21:                return;
  22:            }
  23:        }
  24:  
  25:        //create object for CSVReader and pass the stream
  26:        CSVReader reader = new CSVReader(FileUpload1.PostedFile.InputStream);
  27:        //get the header
  28:        string[] headers = reader.GetCSVLine();        
  29:        DataTable dt = new DataTable();
  30:        //add headers
  31:        foreach (string strHeader in headers)
  32:            dt.Columns.Add(strHeader);
  33:  
  34:        string[] data;
  35:        while ((data = reader.GetCSVLine()) != null)
  36:            dt.Rows.Add(data);
  37:        //bind gridview
  38:        gv.DataSource = dt;
  39:        gv.DataBind();
  40:        
  41:    }

5) create Folder In WebSite CSVLoad for Save Uploaded CSV File.

Thnx

29 Comments »

  1. Pz your above mention code is very difficult to understand pz send me easy code to read one-many csv file and save its record into sqlserver database using C#

    Comment by Sudhanshu — November 11, 2008 @ 11:09 am

  2. hi Sudhanshu,
    you just make the Class CSVReader. after that you can easily use that class inbuilt function which are help.

    thnx

    Comment by patriwala — November 12, 2008 @ 5:42 am

  3. Thanks !

    Nice Article.

    Comment by Yoann. B — November 29, 2008 @ 8:23 pm

  4. Hi, what happen if I have other symbol as delimiter such as “|”?

    Comment by sc — December 15, 2008 @ 5:04 am

    • hi,
      you can change the symbol in the line int nextComma = data.IndexOf(‘,’, fromPos);.

      try it.

      thnx

      Comment by patriwala — December 15, 2008 @ 5:29 am

  5. Thanks!!

    Comment by sc — December 17, 2008 @ 7:38 am

  6. Thanks!

    Comment by DJ — December 26, 2008 @ 9:52 am

  7. Great Code, next time please include a seperate file, copying and pasting took forever because of the line numbers… Be kind to your fellow coders.

    Comment by Bell — February 5, 2009 @ 8:42 pm

  8. good article, but i need the csv file should be uploaded to sql server table

    Comment by satyajit — March 17, 2009 @ 9:28 am

  9. Thank you very much for this very helpful article. Could you please upload the actual code files since copying and pasting from here is not good?

    For the people who wanted to have the CSV file uploaded to a SQL Server table, just do: “BULK INSERT [Table_Name] FROM ‘[File_Name]‘ WITH (FIELDTERMINATOR = ‘,’, ROWTERMINATOR = ‘\n’)”

    - Dmitriy Zasyatkin

    Comment by Dmitriy Zasyatkin — March 23, 2009 @ 8:05 pm

    • How do I import into sql table? I tried the bulk insert, but this is on a web server, the file is in the /app_data folder.

      Comment by James — July 16, 2009 @ 6:20 pm

  10. super

    Comment by sharan — April 2, 2009 @ 8:32 am

  11. Hi,
    I need to upload a csv file from my local hard disk. I couldnt able to execute this code correctly.Can anyone Help me.

    Comment by BAX — April 10, 2009 @ 3:56 am

  12. thanks a lot, for this code, just i have to make it in VB.net ;o)

    Comment by Moksha Solutions — April 15, 2009 @ 9:05 am

  13. really it was helpfull

    Thanks

    Comment by saravana — May 5, 2009 @ 10:05 am

  14. Very nice & simple code, Thanx for sharing these

    Comment by Vicky — May 14, 2009 @ 9:34 pm

  15. This code is exactly what i need.

    Nice article and very helpful.. Thanks for this..

    Comment by Payaso — August 25, 2009 @ 2:42 am

  16. very nice a amigo!

    thanks

    Comment by captaincoooper — August 28, 2009 @ 5:38 am

  17. thnx…
    your code is working nice…
    now i would like to insert that csv file into sql server 2005…you have any idea/code…

    Comment by rahul — September 17, 2009 @ 7:39 pm

    • Dear Rahul,

      that is very easy. just write a code to insert data in sql server within a
      “while ((data = reader.GetCSVLine()) != null)”
      loop.

      Comment by Bipin Singh — September 18, 2009 @ 11:10 am

  18. Heyy,

    thanks a lot for posying this excellent code. it helped me a lot in a very easy way.

    once again thanks a lot for the great code.

    Comment by Bipin Singh — September 18, 2009 @ 11:07 am

  19. This site rocks!

    Comment by Dryer Vent Cleaning — September 19, 2009 @ 1:22 am

  20. Hi, thanks for this code.
    where this csv file is stored?
    CSVLoad means at what location?
    Plz help me…..

    Comment by sonal — October 23, 2009 @ 12:13 pm

    • Hi Sonal,
      please check folder CSVLoad in your web site,csv file stored in..
      create Folder In WebSite CSVLoad for Save Uploaded CSV File which is mention in step 5

      Thnx

      Comment by patriwala — October 23, 2009 @ 12:51 pm

  21. Pls send me Easy code for Uploaded CSV File

    Comment by yugandhar — November 10, 2009 @ 12:04 pm

  22. your code giving wrong out put when
    sentence is like that in CSV
    “It’s my pen, what about you ?”
    Your code will give the put put after reading is
    “It”s my pen, what about you ?”
    Pls give me the solution.

    Comment by Manish — November 18, 2009 @ 6:23 am

  23. thx alot it was very easy and useful i try it now :)

    Comment by zzzz — December 15, 2009 @ 11:56 am


RSS feed for comments on this post. TrackBack URI

Leave a comment

Blog at WordPress.com.