Apr 13, 2010

Upload and import CSV file

 Select File:

<div>
        &nbsp;Select File:
        <asp:FileUpload ID="FileUploader" runat="server" />
        <br />
        <br />
        <asp:Button ID="UploadButton" runat="server" Text="Upload" OnClick="UploadButton_Click" />
        <asp:Button ID="btnsave" runat="server" onclick="btnsave_Click" Text="Save" />
        <br />
        <br />
        <asp:Label ID="Label1" runat="server"></asp:Label></div>

using System; using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq; using System.Data.SqlClient;
using System.IO;
namespace import { public partial class importcontacts : System.Web.UI.Page
{
protected void Page_Load(object sender, EventArgs e)
{
SqlConnection con = new SqlConnection("Data Source=localhost;User id=sa;password=root;database=test");
}
protected void UploadButton_Click(object sender, EventArgs e)
{
if (FileUploader.HasFile)
try {
FileUploader.SaveAs(Server.MapPath("confirm//") + FileUploader.FileName); Label1.Text = "File name: " + FileUploader.PostedFile.FileName + "
" + FileUploader.PostedFile.ContentLength + " kb
" + "Content type: " + FileUploader.PostedFile.ContentType + "
Uploaded Successfully"; 

catch (Exception ex)

Label1.Text = "ERROR: " + ex.Message.ToString(); 
} else 
{
Label1.Text = "You have not specified a file."; 


private void ReadRec() 
{
StreamReader Sr = new StreamReader(Server.MapPath("confirm/") + "params.txt"); System.Text.StringBuilder sb = new System.Text.StringBuilder(); SqlCommand cmd; string s=string.Empty; 
SqlConnection con = new SqlConnection("Data Source=localhost;User id=sa;password=root;database=throwsms");
// do your connection stuff here:
while(!Sr.EndOfStream)
{
s = Sr.ReadLine();
string s1 = "INSERT INTO tblcontact (contact_name,contact_no,client_id) VALUES('" + s.Split(',')[1] + "', '" + s.Split(',')[2] + "',3)"; 
con.Open();
cmd = new SqlCommand(s1, con);
int s2 = cmd.ExecuteNonQuery();
con.Close();

Sr.Close();

protected void btnsave_Click(object sender, EventArgs e) 
{
ReadRec(); 
}




No comments:

Post a Comment