计算多个文件上传的进度条值

本文关键字:文件 计算 | 更新日期: 2023-09-27 17:56:57

我为多个文件上传编写了一个小脚本,包括状态信息的进度条。
现在我想知道如何计算有关上传的所有选定文件的 pogressbar 值。
文件上载适用于按如下方式初始化的后台工作线程:

public Form()
{
    worker = new BackgroundWorker();
    worker.WorkerReportsProgress = true;
    worker.WorkerSupportsCancellation = true;
    worker.DoWork += new DoWorkEventHandler(worker_DoWork);
    worker.ProgressChanged += new ProgressChangedEventHandler(worker_ProgressChanged);
    worker.RunWorkerCompleted += new RunWorkerCompletedEventHandler(worker_RunWorkerCompleted);
}

单击按钮将打开文件对话框,后台工作线程开始工作:

private void button1_Click(object sender, EventArgs e)
{
        if (worker.IsBusy)
        {
            worker.CancelAsync();
        }
        else
        {
            OpenFileDialog od = new OpenFileDialog();
            od.Multiselect = true;
            if (od.ShowDialog() == System.Windows.Forms.DialogResult.OK)
            {
                if (progressBar1.Value == progressBar1.Maximum)
                {
                    progressBar1.Value = progressBar1.Minimum;
                }
                string ftpServerIP = textBox1.Text;
                string ftpUserID = textBox2.Text;
                string ftpPassword = textBox3.Text;
                List<object> arguments = new List<object>();
                arguments.Add(progressBar1.Value);
                arguments.Add(od.FileNames);
                arguments.Add(ftpServerIP);
                arguments.Add(ftpUserID);
                arguments.Add(ftpPassword);
                worker.RunWorkerAsync(arguments);
            }
        }
}

当后台工作者开始工作时,FTP 连接将建立以从文件打开对话框传输所有文件。在以下代码的末尾是我的计算进度条示例,必须更改该进度条以满足文件大小总数:

private void worker_DoWork(object sender, DoWorkEventArgs e)
    {
        List<object> arguments = e.Argument as List<object>;
        int percentFinished = (int)arguments[0];
        string[] fileNames = arguments[1] as string[];
        string ftpServerIP = arguments[2] as string;
        string ftpUserID = arguments[3] as string;
        string ftpPassword = arguments[4] as string;
        while (!worker.CancellationPending && percentFinished < 100)
        {
            foreach (string fileName in fileNames)
            {
                FileInfo fileInf = new FileInfo(fileName);
                // Create FtpWebRequest object from the Uri provided
                reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP + "/" + fileInf.Name));
                // FTP Credentials
                reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
                // By default KeepAlive is true, where the control connection is not closed after a command is executed.
                reqFTP.KeepAlive = false;
                // Specify the command to be executed.
                reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
                // Specify the data transfer type.
                reqFTP.UseBinary = true;
                // Notify the server about the size of the uploaded file
                reqFTP.ContentLength = fileInf.Length;
                // The buffer size is set to 2kb
                int buffLength = 2048;
                byte[] buff = new byte[buffLength];
                int contentLen;
                // Opens a file stream (System.IO.FileStream) to read the file to be uploaded
                FileStream fs = fileInf.OpenRead();
                try
                {
                    // Stream to which the file to be upload is written
                    Stream strm = reqFTP.GetRequestStream();
                    // Read from the file stream 2kb at a time
                    contentLen = fs.Read(buff, 0, buffLength);
                    // Until Stream content ends
                    while (contentLen != 0)
                    {
                        // Write Content from the file stream to the FTP Upload Stream
                        strm.Write(buff, 0, contentLen);
                        contentLen = fs.Read(buff, 0, buffLength);
                    }
                    // Close the file stream and the Request Stream
                    strm.Close();
                    fs.Close();
                }
                catch (Exception ex)
                {
                    MessageBox.Show(ex.Message, "Upload Error");
                }
            }
            // ToDO: Calculate progressBar
            percentFinished++;
            worker.ReportProgress(percentFinished);
            System.Threading.Thread.Sleep(50);
        }
        e.Result = percentFinished;
    }


解决方案
我只需要删除超时,工作人员就会报告正确的值。

 percentFinished++;
 worker.ReportProgress(percentFinished);
 //System.Threading.Thread.Sleep(50);

计算多个文件上传的进度条值

我不确定我是否正确理解你,但让我们试一试。由于string[]数组中有要上传的项目数,因此可以将ProgressBarMaximum设置为开头的元素数。

ProgressBar1.Value = 0;
ProgressBar1.Maximum = fileNames.Length;

在每个循环结束时,您只需使用ProgressBar1.Value += 1;递增进度条的值

private void worker_DoWork(object sender, DoWorkEventArgs e)
{
    //Blah blah blah
    string[] fileNames = arguments[1] as string[];
    ProgressBar1.Value = 0;
    ProgressBar1.Maximum = fileNames.Length;

    while (!worker.CancellationPending && percentFinished < 100)
    {
        foreach (string fileName in fileNames)
        {
            //Blah blah blah
            ProgressBar1.Value += 1;
        }
    }
}

我希望我答对了你的问题。


编辑:对于每个文件,您可能可以围绕BackgroundWorkerProgressChanged事件进行播放。

private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e)
{
    progressBar.Value = e.ProgressPercentage;
}

但请确保您BackgroundWorkerWorkerReportsProgress设置为 true

backgroundWorker2.WorkerReportsProgress = true;