Skip to main content

Importing Text File data into SQL Server database using Asp.Net(C#)

Importing Text File data into SQL Server database using Asp.Net(C#)


Here is code i implemented to import text file data into SQL server database .
.aspx page




<%@ Page Language="C#" MasterPageFile="~/MasterPage.master" AutoEventWireup="true" CodeFile="ImportTEXT.aspx.cs" Inherits="ImportTEXT" Title="Import" %>

<asp:Content ID="Content1" ContentPlaceHolderID="head" Runat="Server">
</asp:Content>
<asp:Content ID="Content3" ContentPlaceHolderID="ContentPlaceHolder1" Runat="Server">
            <table align="center" width="80%" class="tableStyle">
                <caption>
                    <br />
                    <tr>
                        <td align="center" colspan="2">
                            <asp:Label ID="lblHeader" runat="server" CssClass="lblHeader"
                                Text="Import"> </asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td align="center" colspan="2">
                            <asp:Label ID="lblError" runat="server" CssClass="lblText" ForeColor="Red">
                            </asp:Label>
                        </td>
                    </tr>
                    <tr>
                        <td align="right" width="40%">
                            <asp:Label ID="lblDes" runat="server" CssClass="lblText" Text="Upload TEXT File :"></asp:Label>
                        </td>
                        <td>
                            <asp:FileUpload ID="fuTextfile" runat="server" />
                        </td>
                    </tr>
                    <tr>
                        <td>
                            &nbsp;
                        </td>
                    </tr>
                    <tr>
                        <td align="center" colspan="4">
                            <asp:Button ID="btnSave" runat="server" CssClass="buttonStyle" Text="Save"
                                onclick="btnSave_Click" />                          
                        </td>
                    </tr>                  
                </caption>
            </table>
</asp:Content>


----------------------------------------------------------------------------------------------
code .cs file:

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.IO;
using System.Data.OleDb;
using System.Text;
using System.Data.SqlClient;

public partial class ImportTEXT : System.Web.UI.Page
{
    Common objCommon = new Common();

    protected void Page_Load(object sender, EventArgs e)
    {
        if(!IsPostBack)
        {
        }
    }
    protected void btnSave_Click(object sender, EventArgs e)
    {
        try
        {
            if (fuTextfile.HasFile)
            {
                FileInfo fileinfo = new FileInfo(fuTextfile.PostedFile.FileName);
                if (fileinfo.Name.Contains(".txt"))
                {
                    string filename = fileinfo.Name.Replace(".txt", "").ToString();
                    string csvfilepath = ((Server.MapPath("Upload") + "\\") + fileinfo.Name);
                    fuTextfile.SaveAs(csvfilepath);
                    string filepath = (Server.MapPath("Upload") + "\\");
                    string strsql = (("SELECT * FROM [" + fileinfo.Name) + "]");
                    string strCSVConnstring = ("Provider=Microsoft.Jet.OLEDB.4.0;Data Source=" + (filepath + (";" + "Extended Properties=\'text;HDR=YES;\'")));
                    OleDbDataAdapter da = new OleDbDataAdapter(strsql, strCSVConnstring);
                    DataTable dtCSV = new DataTable();
                    DataTable dtSchema = new DataTable();
                    da.FillSchema(dtCSV, SchemaType.Mapped);
                    da.Fill(dtCSV);
                    lblError.Text = dtCSV.Rows.Count.ToString();
                    if (dtCSV.Rows.Count > 0)
                    {
                        string fileFullPath = (filepath + fileinfo.Name);
                        LoadDataToDatabase(filename, fileFullPath, "|");
                    }
                }
            }
        }
        catch (Exception ex)
        {
            objCommon.LogException(ex.Message);
        }
    }
    private void LoadDataToDatabase(string tableName, string fileFullPath, string delimeter)
    {
        string sqlQuery = String.Empty;
        StringBuilder sb = new StringBuilder();
        sb.AppendFormat(string.Format("BULK INSERT {0} ", "tblInventory"));
        sb.AppendFormat(string.Format(" FROM \'{0}\'", fileFullPath));
        sb.AppendFormat(string.Format((" WITH (FIRSTROW = 4, FIELDTERMINATOR = \'{0}\' , ROWTERMINATOR = \'" + ("\n" + "\' )")), delimeter));
        sqlQuery = sb.ToString();

        SqlConnection con = new SqlConnection(@"Data Source=GLOBAL5;Initial Catalog=dbPractice;Integrated Security=True; Connection Timeout=10000");
        con.Open();
        SqlCommand sqlCmd = new SqlCommand(sqlQuery, con);
        sqlCmd.ExecuteNonQuery();
        con.Close();
        con.Open();
        SqlCommand cmd=new SqlCommand("SELECT COUNT(*) FROM tblInventory ", con);
        int i = Convert.ToInt32(cmd.ExecuteScalar());
        lblError.Text = i.ToString();
        lblError.Visible = true;
        con.Close();
        
    }
}

----------------------------------------------------------------------------------------------

And Text file contains :


MaterialNo |  Material Description  |  Qty   | Unit Value  |  Value
 10230       |    xyz..........!               |   2.0   |  1500.35    |   3000.70
like this
Things to remember 

  • Database table should contain same number of columns.
  • Datatype should be appropreate for column datatype according data contained  text file.
I hope this post will help you.
So enjoy it.

--
--
Regards,
Gajanan

Comments

Popular posts from this blog

Asp.Net Web API

What is ASP.NET Web API? ASP.NET Web API is a framework provided by the Microsoft with which we can easily build HTTP services that can reach a broad of clients, including browsers, mobile, IoT devices, etc. ASP.NET Web API provides an ideal platform for building RESTful applications on the .NET Framework.   Difference between ASP.NET Web API and WCF Web AP I is a Framework to build HTTP Services that can reach a board of clients, including browsers, mobile, IoT Devices, etc. and provided an ideal platform for building RESTful applications. It is limited to HTTP based services. ASP.NET framework ships out with the .NET framework and is Open Source. WCF i.e. Windows Communication Foundation is a framework used for building Service Oriented applications (SOA) and supports multiple transport protocol like HTTP, TCP, MSMQ, etc. It supports multiple protocols like HTTP, TCP, Named Pipes, MSMQ, etc. WCF ships out with the .NET Framework. Both Web API and WCF can be self-hosted or can be...

Creating package in Oracle Database using Toad For Oracle

What are Packages in Oracle Database A package is  a group   of procedures, functions,  variables   and  SQL statements   created as a single unit. It is used to store together related objects. A package has two parts, Package  Specification  and Package Body.