Skip to main content
 首页 » 编程设计

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

2024年02月06日20虾米哥

我有以下通过单击按钮调用的函数。该函数读取文件,然后尝试写入 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。在每个 ReadLine 之后,您可以使用 sr.Position 获取当前位置。

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