如何显示从文件读取和写入数据库的进度

时间:2014-06-06 14:48:58

标签: c# sql progress-bar

我有以下从按钮点击调用的功能。该函数读取文件,然后尝试写入SQL表:

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。

如何修改代码以实现我的目标?

1 个答案:

答案 0 :(得分:4)

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

使用这两个数据项,您可以知道已处理的百分比。 (但是,它不会告诉你文件中有多少行,只是你通过总共yKb就是xKb。)