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

时间:2016-07-14 07:19:35

标签: c# winforms file-upload progress-bar

我为多个文件上传编写了一个小脚本,包括状态信息的进度条 现在我想知道如何计算上传所有选定文件的pogressbar值 文件上载与BackgroundWorker一起使用,初始化如下:

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);
}

单击按钮打开文件对话框,BackgroundWorker开始工作:

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);
            }
        }
}

当BackgroundWorker开始工作时,建立FTP连接以从FileOpenDialog传输所有文件。在以下代码的末尾是我的计算进度条示例,必须更改以满足文件大小总计:

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);

1 个答案:

答案 0 :(得分:0)

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

Maximum

在每个循环结束时,您可以使用ProgressBar1.Value = 0; ProgressBar1.Maximum = fileNames.Length;

简单地增加ProgressBar值的值
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; } } } 的{​​{1}}事件进行游戏。

BackgroundWorker

但请确保ProgressChanged的{​​{1}}设置为private void backgroundWorker1_ProgressChanged(object sender, ProgressChangedEventArgs e) { progressBar.Value = e.ProgressPercentage; }

BackgroundWorker