文件传输的进度条

大家好,祝大家好。 我正在为LAN创建文件传输,我想在该文件传输中放置一个进度条,以便用户可以看到传输的进度。 如何根据文件的大小和传输速率操作进度条?

示例:我将10mb文件发送到网络中的另一台计算机。 我希望进度显示剩余时间或完成传输所需的时间。

这里的任何人都可以给我一个关于该做什么的想法吗?

看看http://www.codeproject.com/KB/files/Copy_files_with_Progress.aspx它可能会得到你想要的或至少设置正确的方向。

1)创建一个名为hmmm FileSender的类

2)您的class级将发送分组为块的数据

3)为您的类添加选项,如MaxBlockSize – 它将是您将在一个块中发送的最大数据量

4)创建一个委托OnBlockTransfer或类似的东西

5)制作类似FileSender.Send()方法……

此方法将启动文件发送,在每个块之后,您的类将执行您的委托。 在委托调用的方法中,您可以刷新状态栏。

传输速度很快; 您需要检查系统时间,并计算您发送的数据。

1)你应该循环中的部分发送文件。 因此,您可以确定百分比的进度。

2)您应该在BackgroundWorker执行此操作(它是工具箱中提供的组件)。 后台工作程序有一个ProgressChanged事件,可以通过在DoWork方法中调用ReportProgress来触发该事件。 另外,不要忘记将属性WorkerReportsProgress设置为true。

3)在ProgressChanged事件中,更改您需要的UI以对应当前状态。

最好的方法是将您的传输文件放在一个线程中,并通过调用方法更新您的进度状态。 在我的代码中,我使用FTP传输一个zip文件。 这是我的解决方案和示例代码:

1 – 在你的主表单中你必须有进度条,在我的代码中我将它命名为“prbSendata”

2-调用转移线程:

 Thread oThread = new Thread(Transfer); oThread.Start(this); this.Cursor = Cursors.WaitCursor; 

3-你必须有这样的传输文件:

 private static void Transfer(object obj) { frmMain frmPar = (frmMain)obj; try { string filename=_strStartingPath + @"\" + _strZipFileName + ".zip"; FileInfo fileInf = new FileInfo(filename); string uri = _strFtpAddress + "/" + fileInf.Name; FtpWebRequest reqFTP; // Create FtpWebRequest object from the Uri provided reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri)); // Provide the WebPermission Credintials reqFTP.Credentials = new NetworkCredential(_strFtpUserName, _strFtpPassword); // 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(); // 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); frmPar.prbSendata.Control.Invoke((MethodInvoker)(() =>{ frmPar.prbSendata.Minimum=0; frmPar.prbSendata.Maximum=100; })); // Till Stream content ends long loadSize=0; while (contentLen != 0) { // Write Content from the file stream to the FTP Upload Stream loadSize+=contentLen; frmPar.prbSendata.Control.Invoke((MethodInvoker)(() =>{ frmPar.prbSendata.Value=(int)(loadSize*100/fileInf.Length); })); 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 err) { MessageBox.Show("Error: " + err.Message, "Error", MessageBoxButtons.OK, MessageBoxIcon.Error); } frmPar.txtResult.Invoke((MethodInvoker)(() =>frmPar.Cursor = Cursors.Default)); }