Sign Up

Sign Up to our social questions and Answers Engine to ask questions, answer people’s questions, and connect with other people.

Have an account? Sign In

Have an account? Sign In Now

Sign In

Login to our social questions & Answers Engine to ask questions answer people’s questions & connect with other people.

Sign Up Here

Forgot Password?

Don't have account, Sign Up Here

Forgot Password

Lost your password? Please enter your email address. You will receive a link and will create a new password via email.

Have an account? Sign In Now

You must login to ask a question.

Forgot Password?

Need An Account, Sign Up Here

Please briefly explain why you feel this question should be reported.

Please briefly explain why you feel this answer should be reported.

Please briefly explain why you feel this user should be reported.

Sign InSign Up

The Archive Base

The Archive Base Logo The Archive Base Logo

The Archive Base Navigation

  • SEARCH
  • Home
  • About Us
  • Blog
  • Contact Us
Search
Ask A Question

Mobile menu

Close
Ask a Question
  • Home
  • Add group
  • Groups page
  • Feed
  • User Profile
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Buy Points
  • Users
  • Help
  • Buy Theme
  • SEARCH
Home/ Questions/Q 8889211
In Process

The Archive Base Latest Questions

Editorial Team
  • 0
Editorial Team
Asked: June 14, 20262026-06-14T22:12:23+00:00 2026-06-14T22:12:23+00:00

The following code i believe work to upload csv file to database with the

  • 0

The following code i believe work to upload csv file to database with the following format:

csv format:

john,anderson,m

  1. It will record to TableRef table with insert statement (Done)
  2. Need to insert custId and RefId in the BulkImportDetails based on how many list record in csv. Currently it only insert 1 record.

table 1: TableRef (guid refid(pk, not null), taskname, taskdescription)
table 2: BulkImportDetails (guid custid (pk, not null), guid refid(fk, not null, firstname, surname, age)

how i can insert information based on csv format to both table, please advise. thank you

        /// <summary>
        /// Process the file supplied and process the CSV to a dynamic datatable
        /// </summary>
        /// <param name="fileName">String</param>
        /// <returns>DataTable</returns>
        private static DataTable ProcessCSV(string fileName)
    {

        string connString = ConfigurationManager.ConnectionStrings["DefaultConnection"].ConnectionString;
        int AppID = Convert.ToInt32(ConfigurationManager.AppSettings["AppID"]);
        Guid ReferralID = Guid.NewGuid();
        DateTime date = DateTime.Now;
        using (SqlConnection conn = new SqlConnection(connString))
        {
            conn.Open();

            using (SqlCommand cmd =
            new SqlCommand("INSERT INTO TestTable VALUES(" +
                "refid, @ServerID, @AppID, @CreateDate, @CreatedBy, @CreateDescription, @Description)", conn))
            {
                cmd.Parameters.AddWithValue("@refid", ReferralID);
                cmd.Parameters.AddWithValue("@ServerID", 2);
                cmd.Parameters.AddWithValue("@AppID", AppID);
                cmd.Parameters.AddWithValue("@CreateDate", date);
                cmd.Parameters.AddWithValue("@CreatedBy", "Create by bulk insert");
                cmd.Parameters.AddWithValue("@CreateDescription", "Create by bulk insert");
                cmd.Parameters.AddWithValue("@Description", "Create by bulk insert");


                int rows = cmd.ExecuteNonQuery();

                //rows number of record got inserted
            }


        }

        //Set up our variables 
        string Feedback = string.Empty;
        string line = string.Empty;
        string[] strArray;
        DataTable dt = new DataTable();

        DataRow row;

        // work out where we should split on comma, but not in a sentance
        Regex r = new Regex(",(?=(?:[^\"]*\"[^\"]*\")*(?![^\"]*\"))");

        //Set the filename in to our stream
        StreamReader sr = new StreamReader(fileName);

        //Read the first line and split the string at , with our regular express in to an array
        line = sr.ReadLine();
        strArray = r.Split(line);

        //For each item in the new split array, dynamically builds our Data columns. Save us having to worry about it.

        Array.ForEach(strArray, s => dt.Columns.Add(new DataColumn()));
        dt.Columns.Add("CustID", Type.GetType("System.Guid"));
        dt.Columns.Add("Refid", Type.GetType("System.Guid"));
        dt.Columns["CustID"].SetOrdinal(3);
        dt.Columns["Refid"].SetOrdinal(4);
        //Read each line in the CVS file until it's empty
        while ((line = sr.ReadLine()) != null)
        {
            row = dt.NewRow();

            //add our current value to our data row
            row["CustID"] = Guid.NewGuid();
            row["Refid"] = ReferralID;

            row.ItemArray = r.Split(line);
            dt.Rows.Add(row);
        }
        dt.Columns["CustID"].SetOrdinal(0);

        dt.Columns["Refid"].SetOrdinal(1);
        //Tidy Streameader up
        sr.Dispose();

        //return a the new DataTable
        return dt;


    }




        /// <summary>
        /// Take the DataTable and using WriteToServer(DataTable) send it all to the database table "BulkImportDetails" in one go
        /// </summary>
        /// <param name="dt">DataTable</param>
        /// <returns>String</returns>
        private static String ProcessBulkCopy(DataTable dt)
        {
            string Feedback = string.Empty;
            string connString = ConfigurationManager.ConnectionStrings["DataBaseConnectionString"].ConnectionString;

            //make our connection and dispose at the end    
            using(  SqlConnection conn = new SqlConnection(connString))
            {
                //make our command and dispose at the end
                using (var copy = new SqlBulkCopy(conn))
                {

                        //Open our connection
                        conn.Open();

                        ///Set target table and tell the number of rows
                        copy.DestinationTableName = "BulkImportDetails";
                        copy.BatchSize = dt.Rows.Count;
                        try
                        {
                            //Send it to the server
                            copy.WriteToServer(dt);
                            Feedback = "Upload complete";
                        }
                        catch (Exception ex)
                        {
                            Feedback = ex.Message;
                        }
                }
            }

            return Feedback;
       }
  • 1 1 Answer
  • 0 Views
  • 0 Followers
  • 0
Share
  • Facebook
  • Report

Leave an answer
Cancel reply

You must login to add an answer.

Forgot Password?

Need An Account, Sign Up Here

1 Answer

  • Voted
  • Oldest
  • Recent
  • Random
  1. Editorial Team
    Editorial Team
    2026-06-14T22:12:24+00:00Added an answer on June 14, 2026 at 10:12 pm

    I modified the code as the following:
    http://arranmaclean.wordpress.com/2010/07/20/net-mvc-upload-a-csv-file-to-database-with-bulk-upload/#comment-188

    • 0
    • Reply
    • Share
      Share
      • Share on Facebook
      • Share on Twitter
      • Share on LinkedIn
      • Share on WhatsApp
      • Report

Sidebar

Related Questions

I believe I am having a memory issue using numpy arrays. The following code
following code doesn't work with input: 2 7 add Elly 0888424242 add Elly 0883666666
given the following code... private enum EventTypes { WORK, BREAK, WAIT, CLOSE, COMPLETE }
I have the following code, which I believe should display a progress bar approximating
The following code does not work correctly on Windows (but does on Linux): sock
I love Pascal for its clarity, so believe what the following code snippet along
Insofar as I can tell, the following code should work, creating a <div> element,
I have written the following code and getting the below error, I believe its
Following code produces a nested array as a result for keys containing three items:
Following code takes like 2500 milliseconds on an i7-*3.4 GHz windows-7 64-bit computer to

Explore

  • Home
  • Add group
  • Groups page
  • Communities
  • Questions
    • New Questions
    • Trending Questions
    • Must read Questions
    • Hot Questions
  • Polls
  • Tags
  • Badges
  • Users
  • Help
  • SEARCH

Footer

© 2021 The Archive Base. All Rights Reserved
With Love by The Archive Base

Insert/edit link

Enter the destination URL

Or link to existing content

    No search term specified. Showing recent items. Search or use up and down arrow keys to select an item.