通过FTP方式下载数据时显示进度条的问题

evaseemefly 2011-09-06 02:46:57
我通过FTP的方式访问FTP中的指定路径,并通过指定路径获取了该路径下的所有文件的列表
方法如下:
using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Linq;
using System.Text;
using System.Windows.Forms;
using System.Net;
using System.IO;

namespace 获取指定时间段内的数据
{
class FtpUpDown
{
string ftpServerIP; //服务IP
string ftpUserID; //用户名
string ftpPassword; //密码
FtpWebRequest reqFTP; //实现FTP客户端

/// <summary>
///连接ftp
/// </summary>
/// <param name="path"></param>
private void Connect(string path)
{
//根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFTP.UseBinary = true;
//ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}

/// <summary>
/// 登陆信息
/// </summary>
/// <param name="ftpServerIP"></param>
/// <param name="ftpUserID"></param>
/// <param name="ftpPassword"></param>
public FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
}

/// <summary>
/// 从ftp服务器上获得文件列表
/// </summary>
/// <param name="path"></param>
/// <param name="WRMethods"></param>
/// <returns></returns>
public string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
{

string[] downloadFiles;
StringBuilder result = new StringBuilder(); // StringBuilder是干什么用的? 值为可变字符序列的类似字符串的对象
try
{
Connect("ftp://" + path);
reqFTP.Method = WRMethods;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名

string line = reader.ReadLine(); //有个问题,如何剔除文件夹???
while (line != null)
{
result.Append(line);

result.Append(" ");


line = reader.ReadLine();
}
// to remove the trailing ' '
result.Remove(result.ToString().LastIndexOf(' '), 1);
reader.Close();
response.Close(); //为何要关闭response?
return result.ToString().Split(' ');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
/// <summary>
/// 获取文件大小
/// </summary>
/// <param name="filename"></param>
/// <returns></returns>
public long GetFileSize(string filename)
{
long fileSize = 0;
try
{
FileInfo fileinfo = new FileInfo(filename);
string uri = "ftp://" + ftpServerIP + "/" + fileinfo.Name;
Connect(uri); //连接
reqFTP.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
fileSize = response.ContentLength;
response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return fileSize;
}

/// <summary>
/// 文件下载
/// </summary>
/// <param name="filePath"></param>
/// <param name="fileName"></param>
/// <param name="errorinfo"></param>
/// <returns></returns>
//public bool Download(string filePath, string fileName, out string errorinfo)
public bool Download(string filePath, string fileName, out string errorinfo, System.Windows.Forms.ProgressBar prog)
{
try
{
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + "/" + onlyFileName;
if (File.Exists(newFileName))
{

errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);

return false;

}
else
{
string url = "ftp://" + ftpServerIP + "/" + fileName;

Connect(url);//连接

reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();

Stream ftpStream = response.GetResponseStream();

long cl = response.ContentLength;
//if (prog != null) //(新加的)
//{
// prog.Maximum = (int)cl;
//}
long totalDownLoadByte = 0; //(新加的 )
float percent = 0;
int bufferSize = 2048;

int readCount;
byte[] buffer = new byte[bufferSize];
int osize = ftpStream.Read(buffer, 0, (int)buffer.Length); //这句是什么意思?
while (osize > 0) //(新加的)
{
totalDownLoadByte = osize + totalDownLoadByte;
//if (prog != null)
//{
// prog.Value = (int)totalDownLoadByte;
//}
osize = ftpStream.Read(buffer, 0, (int)buffer.Length);
percent = (float)totalDownLoadByte / (float)totalDownLoadByte * 100;

}


readCount = ftpStream.Read(buffer, 0, bufferSize);

FileStream outputStream = new FileStream(newFileName, FileMode.Create);

while (readCount > 0)
{

outputStream.Write(buffer, 0, readCount);

readCount = ftpStream.Read(buffer, 0, bufferSize);

}

ftpStream.Close();

outputStream.Close();

response.Close();

errorinfo = "";

return true;
}

}

catch (Exception ex)

{

errorinfo = string.Format("因{0},无法下载", ex.Message);

return false;

}

}

}
}


...全文
360 5 打赏 收藏 转发到动态 举报
写回复
用AI写文章
5 条回复
切换为时间正序
请发表友善的回复…
发表回复
q376202990 2012-01-03
  • 打赏
  • 举报
回复
恩不错,谢谢了
evaseemefly 2011-09-06
  • 打赏
  • 举报
回复
有哪位知道为什么吗
成成 2011-09-06
  • 打赏
  • 举报
回复
我也想知道结果。
wangyue4 2011-09-06
  • 打赏
  • 举报
回复
http://download.csdn.net/source/3554276
我自己写的ftp下载带滚动条,这是用来实现winform的自动更新!
evaseemefly 2011-09-06
  • 打赏
  • 举报
回复
以上是FTP操作的一些类,现在有这么个问题就是我想在下载的时候实现进度条的显示,建立了一个委托:


private void 下载ToolStripMenuItem_Click(object sender, EventArgs e)
{
//string temp;
thdAddFile = new Thread(new ThreadStart(SetAddFile));
thdAddFile.Start();

}

public void SetAddFile( )
{
this.Invoke(new AddFile(RunAddFile));
}

/// <summary>
/// 下载选定文件
/// </summary>
public void RunAddFile()
{
string temp;
string targetDownLoadPath=null; //将要下载到的指定路径

/*
* 若选定的是一个对象
*/
if (listView1.SelectedItems.Count == 1)
{
//文件名即为listView中选定的那个对象
string filename = listView1.SelectedItems[0].Text;
if (MessageBox.Show("是否下载选定文件?", "选项", MessageBoxButtons.OKCancel, MessageBoxIcon.Question) == DialogResult.OK)
{
this.toolStripProgressBar1.Value = 0;
this.toolStripProgressBar1.Minimum = 0;
targetDownLoadPath = path;
FtpUpDown ftp = new FtpUpDown(ip, id, pwd);

//获取是否下载成功的中间变量
//返回的temp是带有异常错误信息的string变量
//bool temp_result = ftp.Download(targetDownLoadPath, filename, out temp);
bool temp_result = ftp.Download(targetDownLoadPath, filename, out temp, form1.progressBar1);

this.listBox1.Items.Add("正在下载" + filename);

ListView listview2 = new ListView();

toolStripProgressBar1.Value = 100;
if (temp_result == true)
{
MessageBox.Show("下载成功!", "提示", MessageBoxButtons.OK);

this.listBox1.Items.Add(filename + "下载成功!");
this.listBox1.Items.Add(filename + "已经保存在" + targetDownLoadPath);

}
else if (temp_result == false)
{
MessageBox.Show("下载失败!", "提示", MessageBoxButtons.OK);
if (temp.Length > 40)
{
this.listBox1.Items.Add(temp.Substring(0, 40));
this.listBox1.Items.Add(temp.Substring(41));

}
else if (temp.Length < 40)
{
this.listBox1.Items.Add(temp);

}
}
toolStripProgressBar1.Value = 0;
this.listBox1.Items.Add("------------------------");
//CouldClassify为是否需要分类存储的中间变量,这里设置为true即为执行分类存储操作
CouldClassify = true;
//CouldShowDialog为是否需要弹出ShowDialog这个对话框“是否需要分类存储?”
CouldShowDialog = true;
ClassifySave(filename, targetDownLoadPath, "D:\\GNSS数据", "2011"); //此处的gnss数据需要修改
}
else
{

}
listView1.SelectedItems.Clear();

}

以上只是程序代码中的一部分,请问在RunAddFil方法中的:
bool temp_result = ftp.Download(targetDownLoadPath, filename, out temp, form1.progressBar1);
这里我在FtpUpDown这个类的Download方法中的Download方法中给他传入的参数设置为Forms.ProgressBar类型的,但是为何运行时会提示我没有实例化对象呢?这个form1我是设置为全局变量的:public static Form1 form1;
public bool Download(string filePath, string fileName, out string errorinfo, System.Windows.Forms.ProgressBar prog)

还有就是请给位大大帮忙分析一下,如何实现进度条的显示。谢谢

110,534

社区成员

发帖
与我相关
我的任务
社区描述
.NET技术 C#
社区管理员
  • C#
  • Web++
  • by_封爱
加入社区
  • 近7日
  • 近30日
  • 至今
社区公告

让您成为最强悍的C#开发者

试试用AI创作助手写篇文章吧