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

Blog at WordPress.com.