如何显示从文件读取和写入数据库的进度 [英] How to show progress of reading from a file and writing to a database

查看:56
本文介绍了如何显示从文件读取和写入数据库的进度的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有以下函数,它是通过单击按钮调用的.该函数读取文件,然后尝试写入 SQL 表:

I have the following function which is called from a button click. The function reads the file and then attempts to write to a SQL table:

public void saveCSV()
{
    lblCSVStatus.Text = "";
    worker = new BackgroundWorker { WorkerReportsProgress = true };
    worker.DoWork += (sender, args) =>
    {
        tbTable.Invoke((MethodInvoker)delegate
        {
            tbTable.Enabled = false;
        });

        myConnection = new SqlConnection(cString);
        myConnection.Open();

        /* BEGIN READING CSV FILE */
        StreamReader sr = new StreamReader(tbCSVFileLocation.Text.ToString());
        string line = sr.ReadLine();
        string[] value = line.Split(',');
        DataTable dt = new DataTable();
        DataRow row;

        foreach (string dc in value)
        {
            dt.Columns.Add(new DataColumn(dc));
        }

        while (!sr.EndOfStream)
        {
            value = sr.ReadLine().Split(',');
            if (value.Length == dt.Columns.Count)
            {
                row = dt.NewRow();
                row.ItemArray = value;
                dt.Rows.Add(row);
            }
        }
        /* END READING CSV FILE */

        /* CREATE TABLE IF DOESN'T EXIST AND WRITE (APPEND/OVERWRITE) THE DATA */
        string exists = null;
        try
        {
            SqlCommand cmd = 
                new SqlCommand("SELECT * FROM sysobjects where name = '" + tbTable.Text + "'",
                               myConnection);
            exists = cmd.ExecuteScalar().ToString();
        }
        catch (Exception exce)
        {
            exists = null;
        }

        if (exists == null)
        {
            foreach (DataColumn dc in dt.Columns)
            {
                if (exists == null)
                {
                    SqlCommand createtable =
                        new SqlCommand("CREATE TABLE " + tbTable.Text + " (" + dc.ColumnName + " varchar(MAX))",
                                       myConnection);
                    createtable.ExecuteNonQuery();
                    exists = tbTable.Text;
                }
                else
                {
                    SqlCommand addcolumn =
                        new SqlCommand("ALTER TABLE " + tbTable.Text + " ADD [" + dc.ColumnName + "] varchar(MAX)",
                                       myConnection);
                    addcolumn.ExecuteNonQuery();
                }
            }

            using (SqlBulkCopy bulkCopy = new SqlBulkCopy(myConnection))
            {
                try
                {
                    bulkCopy.DestinationTableName = tbTable.Text;
                    bulkCopy.WriteToServer(dt);
                    lblCSVStatus.Invoke((MethodInvoker)delegate
                    {
                        lblCSVStatus.Text = "Successfully Updated " + tbTable.Text + " Table";
                        lblCSVStatus.ForeColor = System.Drawing.Color.Green;
                    });
                    tbTable.Invoke((MethodInvoker)delegate
                    {
                        tbTable.Enabled = true;
                    });
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message.ToString(),
                                    "Program Error",
                                    MessageBoxButtons.OK,
                                    MessageBoxIcon.Exclamation);
                    lblCSVStatus.Invoke((MethodInvoker)delegate
                    {
                        lblCSVStatus.Text = "Failed to Update " + tbTable.Text + " Table";
                        lblCSVStatus.ForeColor = System.Drawing.Color.Red;
                    });
                    tbTable.Invoke((MethodInvoker)delegate
                    {
                        tbTable.Enabled = true;
                    });
                }
            }
        }
        else
        {
            if (rbAppend.Checked == true)
            {
                using (SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection))
                {
                    try
                    {
                        bulkcopy.DestinationTableName = tbTable.Text;
                        bulkcopy.WriteToServer(dt);
                        lblCSVStatus.Invoke((MethodInvoker)delegate
                        {
                            lblCSVStatus.Text = "Successfully Updated " + tbTable.Text + " Table";
                            lblCSVStatus.ForeColor = System.Drawing.Color.Green;
                        });
                        tbTable.Invoke((MethodInvoker)delegate
                        {
                            tbTable.Enabled = true;
                        });
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString(),
                                        "Program Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Exclamation);
                        lblCSVStatus.Invoke((MethodInvoker)delegate
                        {
                            lblCSVStatus.Text = "Failed to Update " + tbTable.Text + " Table";
                            lblCSVStatus.ForeColor = System.Drawing.Color.Red;
                        });
                        tbTable.Invoke((MethodInvoker)delegate
                        {
                            tbTable.Enabled = true;
                        });
                    }
                }
            }
            if (rbUpdate.Checked == true)
            {
                SqlCommand truncateTable = new SqlCommand("TRUNCATE TABLE " + tbTable.Text + "",
                                                          myConnection);
                truncateTable.ExecuteNonQuery();
                using (SqlBulkCopy bulkcopy = new SqlBulkCopy(myConnection))
                {
                    try
                    {
                        bulkcopy.DestinationTableName = tbTable.Text;
                        bulkcopy.WriteToServer(dt);
                        lblCSVStatus.Invoke((MethodInvoker)delegate
                        {
                            lblCSVStatus.Text = "Successfully Updated " + tbTable.Text + " Table";
                            lblCSVStatus.ForeColor = System.Drawing.Color.Green;
                        });
                        tbTable.Invoke((MethodInvoker)delegate
                        {
                            tbTable.Enabled = true;
                        });
                    }
                    catch (Exception ex)
                    {
                        MessageBox.Show(ex.Message.ToString(),
                                        "Program Error",
                                        MessageBoxButtons.OK,
                                        MessageBoxIcon.Exclamation);
                        lblCSVStatus.Invoke((MethodInvoker)delegate
                        {
                            lblCSVStatus.Text = "Failed to Update " + tbTable.Text + " Table";
                            lblCSVStatus.ForeColor = System.Drawing.Color.Red;
                        });
                        tbTable.Invoke((MethodInvoker)delegate
                        {
                            tbTable.Enabled = true;
                        });
                    }
                }
            } 
         }

         myConnection.Close();

         sr.Close();
    };
    worker.ProgressChanged += (sender, args) =>
    {
        //lblCSVStatus.Text = "Working...";
        pbUpdate.Value = args.ProgressPercentage;
    };

    worker.RunWorkerAsync();
}

我正在使用 BackgroundWorker 来显示操作的进度.我正在尝试根据操作将 ProgressBar pbUpdate 值从 0 更新为 100.

I am making use of the BackgroundWorker to show the progress of the action. I am trying to update the ProgressBar pbUpdate value from 0 to 100 based on the action.

如何修改代码以实现我想要做的事情?

How can I modify the code to achieve what I am looking to do?

推荐答案

打开 StreamReader 后,您可以从中获取长度:sr.Length.在每个 ReadLine 之后,您可以使用 sr.Position 获取当前位置.

Once you open the StreamReader, you can get the length from it: sr.Length. After each ReadLine, you can get the current position with sr.Position.

有了这两个数据项,您就知道处理了多少百分比.(但是,它不会告诉您文件中有多少行,只是告诉您总共是 xKb 到 yKb.)

With those two data items you know what percentage has been processed. (However, it doesn't tell you how many lines there are in the file, just that you are xKb through a total of yKb.)

这篇关于如何显示从文件读取和写入数据库的进度的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆