Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/redis/2.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
C# 如何显示从文件读取和写入数据库的进度_C#_Sql_Progress Bar - Fatal编程技术网

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

C# 如何显示从文件读取和写入数据库的进度,c#,sql,progress-bar,C#,Sql,Progress Bar,我有下面的函数,它是通过单击按钮调用的。函数读取文件,然后尝试写入SQL表: public void saveCSV() { lblCSVStatus.Text = ""; worker = new BackgroundWorker { WorkerReportsProgress = true }; worker.DoWork += (sender, args) => { tbTable.Invoke((MethodInvoker)deleg

我有下面的函数,它是通过单击按钮调用的。函数读取文件,然后尝试写入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


如何修改代码以实现我想要的功能?

打开StreamReader后,可以从中获取长度:
sr.length
。每次读取行后,您可以使用
sr.position
获取当前位置


对于这两个数据项,您知道已处理的百分比。(但是,它不会告诉您文件中有多少行,只告诉您总共是xKb。)

打开StreamReader后,您可以从中获取长度:
sr.length
。每次读取行后,您可以使用
sr.position
获取当前位置

对于这两个数据项,您知道已处理的百分比。(但是,它并没有告诉您文件中有多少行,只告诉您总共有多少行是xKb。)