文件传输进度条
本文关键字:传输 文件 | 更新日期: 2023-09-27 18:18:31
大家好。我现在正在创建一个局域网文件传输,我想在文件传输中添加一个进度条,这样用户就可以看到传输的进度。如何根据文件的大小和传输速率来操作进度条?
示例:我正在向网络中的另一台计算机发送一个10mb的文件。我希望进度显示剩余时间或完成传输需要多长时间。
这里有人能给我一个建议吗?看看http://www.codeproject.com/KB/files/Copy_files_with_Progress.aspx,它可能会让你得到你想要的,或者至少在正确的方向。
1)创建一个名为hmmm FileSender的类
2)你的类将发送数据分组到块
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));
}