进度条未在其他表单上更新

时间:2018-05-21 06:12:03

标签: c# winforms

我必须从特定文件夹中删除文件和子文件夹,而删除文件进度条应显示另一个表单上的进度条。

我为此接受了背景工作者。进度条值正在更改为例外,但屏幕上的进度条未显示更新百分比。

我正在使用visual studio 2005。因为这是旧项目。

private void EmptyFolder(DirectoryInfo directoryInfo, long totalSize, frmProgress frmProgressLbl, ref long deletedSize)
{
    short percent;
    //long deletedSize=0;
    try
    {
        foreach (FileInfo file in directoryInfo.GetFiles())
        {
            try
            {
                deletedSize += file.Length;
                file.Delete();
                percent = Convert.ToInt16((deletedSize * 100) / totalSize);
                frmProgressLbl.Percent = percent;
            }
            catch (Exception ex)
            {

            }
        }
        foreach (DirectoryInfo subfolder in directoryInfo.GetDirectories())
        {
            EmptyFolder(subfolder, totalSize,frmProgressLbl,ref deletedSize);
        }
    }
    catch (Exception ex)
    {

    }
}

以下是进度条所在的表单上的代码。

public partial class frmProgress : Form
{
    private short percent;
    public short Percent { set { percent = value; } }
    private BackgroundWorker bgWorker;
    public frmProgress()
    {
        InitializeComponent();

        this.bgWorker = new BackgroundWorker();
        this.bgWorker.WorkerReportsProgress = true;
        this.bgWorker.WorkerSupportsCancellation = true;
        this.bgWorker.DoWork += new DoWorkEventHandler(bgWorker_DoWork);
        this.bgWorker.RunWorkerAsync();
    }

    private void frmProgress_Load(object sender, EventArgs e)
    {
        this.label1.Text = "Deleting Files...";
        this.bgWorker.RunWorkerAsync();
    }
    void bgWorker_DoWork(object sender, DoWorkEventArgs e)
    {
        this.progressBar1.Value = percent;
    }
}

您的帮助可能会受到赞赏。

2 个答案:

答案 0 :(得分:2)

您可以借助以下代码实现

private void buttonDelete_Click(object sender, EventArgs e)
{
    // Start your task
    backgroundWorker.RunWorkerAsync();
}

private void backgroundWorker_DoWork(object sender, DoWorkEventArgs e)
        {                
                #region Write logic to delete files in this region

                var totalFiles = 100;

                for (int i = 1; i <= totalFiles; i++)
                {                    
                    // Report progress
                    backgroundWorker.ReportProgress((i * totalFiles) / 100);

                    System.Threading.Thread.Sleep(200);
                } 

                #endregion                
        }

private void backgroundWorker_ProgressChanged(object sender, ProgressChangedEventArgs e)
        {                
                // Update prgores bar
                progressBar.Value = e.ProgressPercentage;                
        }  

private void backgroundWorker_RunWorkerCompleted(object sender, RunWorkerCompletedEventArgs e)
        {                
                // Do further process when your task is completed                
        }   

答案 1 :(得分:0)

我写了删除frmProgress表单上的文件的方法,它解决了我的问题。

感谢你们所有人。