c#实现ftp上传、删除、下载、新建等功能
#region 初始化
public FTPForm()
{
InitializeComponent();
//this.FormBorderStyle = System.Windows.Forms.FormBorderStyle.None;
}
/// <summary>
/// ftp实例相应对象
/// </summary>
FtpWebRequest ftpmodel = null;
/// <summary>
/// ftp 请求对象
/// </summary>
FtpWebRequest Request = null;
/// <summary>
/// 用户名
/// </summary>
string username;
/// <summary>
/// 密码
/// </summary>
string pwd;
/// <summary>
/// ftp 地址
/// </summary>
string ftpip;
/// <summary>
/// 记录月份对应的数字
/// </summary>
Dictionary<string, string> GetYue = new Dictionary<string, string>();
/// <summary>
/// 记录文件夹(用于返回上一层文件夹)
/// </summary>
List<string> openFolder = new List<string>();
private void FTPForm_Load(object sender, EventArgs e)
{
InitStyle();
}
/// <summary>
/// 载入某某些属性
/// </summary>
private void InitStyle()
{
openFolder.Clear();
GetYue.Clear();
Button AA = new Button();
AA.Click = new EventHandler(AA_Click);
this.CancelButton = AA;
Button BB = new Button();
BB.Click = new EventHandler(BB_Click);
this.AcceptButton = BB;
//listview 绑定列
InitListview();
//记录月份对应的数字
GetYue.Add("Jan", "1");
GetYue.Add("Feb", "2");
GetYue.Add("Mar", "3");
GetYue.Add("Apr", "4");
GetYue.Add("May", "5");
GetYue.Add("Jun", "6");
GetYue.Add("Jul", "7");
GetYue.Add("Aug", "8");
GetYue.Add("Sep", "9");
GetYue.Add("Oct", "10");
GetYue.Add("Nov", "11");
GetYue.Add("Dec", "12");
}
/// <summary>
/// 编辑显示下载文件的列表
/// </summary>
private void InitListview()
{
//显示方式
lvlist_down.View = View.Details;
//显示边线
lvlist_down.GridLines = true;
//清空列
lvlist_down.Columns.Clear();
//设置标题样式
lvlist_down.HeaderStyle = ColumnHeaderStyle.Clickable;
//绑定列
//第一列
ColumnHeader ch01 = new ColumnHeader();
ch01.Text = "文件名";
ch01.TextAlign = HorizontalAlignment.Center;
ch01.Width = (int)(lvlist_down.Width * 0.4) ;
//二
ColumnHeader ch02 = new ColumnHeader();
ch02.Text = "大小";
ch02.TextAlign = HorizontalAlignment.Center;
ch02.Width = (int)(lvlist_down.Width * 0.6/4);
//三
ColumnHeader ch03 = new ColumnHeader();
ch03.Text = "类型";
ch03.TextAlign = HorizontalAlignment.Center;
ch03.Width = (int)(lvlist_down.Width * 0.6/4);
//四
ColumnHeader ch04 = new ColumnHeader();
ch04.Text = "时间";
ch04.TextAlign = HorizontalAlignment.Center;
ch04.Width = (int)(lvlist_down.Width * 0.6/3);
//五
ColumnHeader ch05 = new ColumnHeader();
ch05.Text = "属性";
ch05.TextAlign = HorizontalAlignment.Center;
ch05.Width = (int)(lvlist_down.Width * 0.6 / 4);
this.lvlist_down.Columns.Add(ch01);
this.lvlist_down.Columns.Add(ch02);
this.lvlist_down.Columns.Add(ch03);
this.lvlist_down.Columns.Add(ch04);
this.lvlist_down.Columns.Add(ch05);
}
//菜单键
void BB_Click(object sender, EventArgs e)
{
}
//单机退出按键
void AA_Click(object sender, EventArgs e)
{
try
{
this.Close();
}
catch { }
}
#endregion
#region 连接ftp服务器
//测试ftp服务器连通性
private void bt_testliantong_Click(object sender, EventArgs e)
{
openFolder.Clear();
ftpmodel = null;
ConnectFTP("/" tb_lujing.Text);
GetDirList("/" tb_lujing.Text);
}
/// <summary>
/// 连接ftp
/// </summary>
private void ConnectFTP(string dirname)
{
try
{
if (ftpmodel == null)
{
//确定登录信息
username = tb_username.Text;
pwd = tb_pwd.Text;
ftpip = tp_ftpdizhi.Text;
string url = "ftp://" tp_ftpdizhi.Text;
if (dirname.Trim() != "")
{
url = dirname;
string[] ss = dirname.Substring(1).Split('/');
openFolder.Insert(0, "");
foreach (string s in ss)
{
openFolder.Insert(0, s);
}
}
else
openFolder.Insert(0, "");
//打开连接
FtpWebResponse frsp= open(url, WebRequestMethods.Ftp.ListDirectoryDetails);
frsp.Close();
//显示登录信息
tb_showftpdizhi.Text = "地址:ftp://" tp_ftpdizhi.Text "/" tb_lujing.Text;
tb_showuser.Text = "用户名:" tb_username.Text;
tb_showdenglushijian.Text = "登录时间:" System.DateTime.Now.ToString("yyyy-MM-dd hh:mm:ss");
}
}
catch (Exception ee)
{
ftpmodel = null;
MessageBox.Show("连接失败!---" ee.Message);
}
}
/// <summary>
/// 打开一个连接(下载的时候使用)
/// </summary>
/// <param name="url">连接地址</param>
/// <param name="metnod"></param>
/// <returns></returns>
private FtpWebResponse open(string url, string metnod)
{
ftpmodel = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
// 指定数据传输类型
ftpmodel.UseBinary = true;
ftpmodel.UsePassive = true;
ftpmodel.KeepAlive = false;
// ftp用户名和密码
ftpmodel.Credentials = new NetworkCredential(username, pwd);
ftpmodel.Method = metnod;
FtpWebResponse frsp = (FtpWebResponse)ftpmodel.GetResponse();
return frsp;
}
/// <summary>
/// 打开一个连接(上传 新建文件的时候使用)
/// </summary>
/// <param name="uri"></param>
/// <param name="FtpMathod"></param>
/// <returns></returns>
private FtpWebRequest OpenRequest(string uri, string FtpMathod)
{
try
{
Request = (FtpWebRequest)FtpWebRequest.Create(uri);
Request.KeepAlive = false;
Request.UsePassive = true;
Request.Method = FtpMathod;
Request.Credentials = new NetworkCredential(username, pwd);
return Request;
}
catch (Exception ep)
{
throw ep;
}
}
#endregion
#region 获取文件ftp指定区域内的文件列表
bool openstate = true;
/// <summary>
/// 获取文件ftp指定区域内的文件列表
/// </summary>
private void GetDirList(string dirname)
{
openstate = true;
StreamReader sr = null;
FtpWebResponse wbs = null;
try
{
if (ftpmodel == null)
{
MessageBox.Show("请先连接ftp服务器!");
}
else
{
string url = GetFtpFpath(dirname);
//显示列表
wbs = open(url, WebRequestMethods.Ftp.ListDirectoryDetails);
sr = new StreamReader(wbs.GetResponseStream(), Encoding.Default);
string line = sr.ReadLine();
Invoke((EventHandler)(delegate {
lvlist_down.Items.Clear();
}));
while (line != null)
{
string[] infors = line.Split(new string[1] {" "}, System.StringSplitOptions.RemoveEmptyEntries);
if (infors.Length <= 2 || infors[8] == ".." || infors[8] == ".")
{
line = sr.ReadLine();
continue;
}
string filename = "";
if (infors.Length > 9)
{
int index = line.LastIndexOf(infors[8]);
filename = filename line.Substring(index);
}
else
{
filename = infors[8];
}
FileListInfo fli = new FileListInfo();
fli.属性 = infors[0];
fli.大小 = infors[4];
string yue = "";
GetYue.TryGetValue(infors[5], out yue);
fli.月 = yue;
fli.日 = infors[6];
string nianr = infors[7];
if (nianr.Contains(':'))
nianr = DateTime.Now.Year "-" fli.月 "-" fli.日 " " infors[7];
else
nianr = infors[7] "-" fli.月 "-" fli.日 " 00:00";
if (fli.属性.Substring(0, 1) == "d")
fli.类型 = "文件夹";
else
fli.类型 = "文件";
fli.年_时间 = nianr;
fli.文件名称 = filename;
//listview 添加数据行
ListViewItem lvi = new ListViewItem();
lvi.Text = fli.文件名称;
lvi.SubItems.Add(fli.大小);
lvi.SubItems.Add(fli.类型);
lvi.SubItems.Add(fli.年_时间);
lvi.SubItems.Add(fli.属性);
Invoke((EventHandler)(delegate {
lvlist_down.Items.Add(lvi);
}));
line = sr.ReadLine();
}
sr.Close();
wbs.Close();
Invoke((EventHandler)(delegate {
tb_showftpdizhi.Text = "地址:" url;
}));
#region 写入本地数据
////写入本地数据
//FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate);
//StreamWriter sw = new StreamWriter(fs);
//while (line != null)
//{
// sw.WriteLine(line);
// line = sr.ReadLine();
//}
//sw.Close();
//fs.Close();
#endregion
}
}
catch(Exception ex)
{
MessageBox.Show("出现错误----" ex.Message);
openstate = false;
return;
}
}
/// <summary>
/// 获取当前目录下的文件和文件夹信息
/// </summary>
/// <returns>List</returns>
private List<string> GetFileDirList(string type)
{
StreamReader sr = null;
FtpWebResponse wbs = null;
try
{
if (ftpmodel == null)
{
MessageBox.Show("请先连接ftp服务器!");
}
else
{
List<string> l_fildirlist = new List<string>();
string url = GetFtpFpath(GetFilePath());
//显示列表
wbs = open(url, WebRequestMethods.Ftp.ListDirectoryDetails);
sr = new StreamReader(wbs.GetResponseStream(), Encoding.Default);
string line = sr.ReadLine();
while (line != null)
{
string[] infors = line.Split(new string[1] { " " }, System.StringSplitOptions.RemoveEmptyEntries);
if (infors.Length <= 2 || infors[8] == ".." || infors[8] == ".")
{
line = sr.ReadLine();
continue;
}
string filename = "";
if (infors.Length > 9)
{
int index = line.LastIndexOf(infors[8]);
filename = filename line.Substring(index);
}
else
{
filename = infors[8];
}
if (type.Trim() == "文件夹" && infors[0].Substring(0, 1) == "d")
l_fildirlist.Add(filename.ToLower());
if (type.Trim() == "文件" && infors[0].Substring(0, 1) != "d")
l_fildirlist.Add(filename);
line = sr.ReadLine();
}
sr.Close();
wbs.Close();
#region 写入本地数据
////写入本地数据
//FileStream fs = new FileStream("test.txt", FileMode.OpenOrCreate);
//StreamWriter sw = new StreamWriter(fs);
//while (line != null)
//{
// sw.WriteLine(line);
// line = sr.ReadLine();
//}
//sw.Close();
//fs.Close();
#endregion
return l_fildirlist;
}
}
catch
{
}
return null;
}
private string GetFtpFpath(string dirname)
{
string url = "ftp://" ftpip;
if (dirname.Trim() != "")
{
if (dirname.Substring(0, 1) == "/")
dirname = dirname.Substring(1);
if (dirname.Trim() != "")
url = "/" dirname;
}
return url;
}
#endregion
#region 下载文件 文件夹
/// <summary>
/// 下载文件
/// </summary>
/// <param name="RemoteFileName">远程文件名称</param>
private void DownloadFile(object RemoteFileName)
{
try
{
FileListInfo fll = RemoteFileName as FileListInfo;
string url = GetFtpFpath(GetFilePath()) "/" fll.文件名称;
string filename = "";
Invoke((EventHandler)(delegate {
SaveFileDialog sf = new SaveFileDialog();
sf.FileName = fll.文件名称;
sf.InitialDirectory = Environment.GetFolderPath(Environment.SpecialFolder.DesktopDirectory);//默认路径桌面
if (sf.ShowDialog() == DialogResult.Cancel) return;
filename = sf.FileName;
}));
Stream mubiaostream = new FileStream(filename, FileMode.Create);
FtpWebResponse fws = open(url, WebRequestMethods.Ftp.DownloadFile);
Stream streader = fws.GetResponseStream();
byte[] buffer = new byte[1024];
int bytesRead = streader.Read(buffer, 0, buffer.Length);//从当前流中读取数据
int tatalread = 0;
while (bytesRead != 0)
{
tatalread = bytesRead;
mubiaostream.Write(buffer, 0, bytesRead);//将读取的数据写入目标流中
mubiaostream.Seek(0, SeekOrigin.End);//设置当前流的位置 从零开始
bytesRead = streader.Read(buffer, 0, buffer.Length);
Invoke((EventHandler)(delegate {
pgb_jindu.Maximum = int.Parse(fll.大小);
pgb_jindu.Value = tatalread;
lb_baifenbi.Text = ((int)((double)(pgb_jindu.Value) / (double)(pgb_jindu.Maximum) * 100)).ToString() "%";
}));
}
mubiaostream.Close();
streader.Close();
fws.Close();
Invoke((EventHandler)(delegate {
pgb_jindu.Maximum = 0;
pgb_jindu.Value = 0;
lb_baifenbi.Text = "0%";
}));
}
catch
{
}
}
/// <summary>
/// 下载一个文件夹
/// </summary>
/// <param name="dirinfo"></param>
private void DownDir(object dirinfo)
{
}
#endregion
#region 上传文件 文件夹
/// <summary>
/// 上传文件
/// </summary>
/// <param name="fileinf"></param>
private void UpLoadFile(object fileinf)
{
try
{
FileListInfo fli = fileinf as FileListInfo;
//本地文件路径
string fileapth = fli.path;
//获取本地文件名
string filename = fli.文件名称.Replace("#","Sharp");
//远程路径
string url = GetFtpFpath(GetFilePath()) "/" filename;
//判断远程文件是否存在
if (GetFileDirList("文件").Contains(filename))
{
MessageBox.Show("远程服务器上文件成已存在!");
return;
}
//获取远程流
FtpWebRequest fwr = OpenRequest(url, WebRequestMethods.Ftp.UploadFile);
//获取远程文件流
Stream uploadstream = fwr.GetRequestStream();
//打开本地文件流
Stream localfilestr = new FileStream(fileapth, FileMode.Open);
byte[] buffer = new byte[1024];
int byteread = localfilestr.Read(buffer, 0, buffer.Length);
int totalread = 0;
while (byteread != 0)
{
totalread = byteread;
uploadstream.Write(buffer, 0, byteread);
byteread = localfilestr.Read(buffer, 0, buffer.Length);
Invoke((EventHandler)(delegate
{
pgb_jindu.Maximum = int.Parse(fli.大小);
pgb_jindu.Value = totalread;
lb_baifenbi.Text = ((int)((double)(pgb_jindu.Value) / (double)(pgb_jindu.Maximum) * 100)).ToString() "%";
}));
}
localfilestr.Close();
uploadstream.Close();
Invoke((EventHandler)(delegate {
GetDirList(GetFilePath());
pgb_jindu.Maximum = 0;
pgb_jindu.Value = 0;
lb_baifenbi.Text = "0%";
}));
}
catch(Exception ee)
{
throw ee;
}
}
/// <summary>
/// 上传文件夹
/// </summary>
/// <param name="foldername"></param>
private void UploadFolder()
{
List<string> lldir = GetFileDirList("文件夹");
FolderBrowserDialog fbd = new FolderBrowserDialog();
fbd.RootFolder = Environment.SpecialFolder.DesktopDirectory;
if (fbd.ShowDialog() == DialogResult.Cancel) return;
Thread tt = new Thread(StartUpload);
tt.IsBackground = true;
DirectoryInfo dd = new DirectoryInfo(fbd.SelectedPath);
tt.Start(dd);
Invoke((EventHandler)(delegate {
ListViewItem lvi = new ListViewItem();
lvi.Text = fbd.SelectedPath;
lvi.SubItems.Add("0");
lvi.SubItems.Add("上传到:" GetFtpFpath(GetFilePath()));
lvlist_show.Items.Add(lvi);
}));
}
private void StartUpload(object infos)
{
ViewDirectory(infos);
Invoke((EventHandler)(delegate {
tb_showstate.Text = "";
MessageBox.Show("上传完成!");
}));
}
/// <summary>
/// 子目录和文件
/// </summary>
/// <param name="info"></param>
private void ViewDirectory(object infos)
{
DirectoryInfo info = infos as DirectoryInfo;
try
{
//目录名字
string name = info.Name.Replace("#", "Sharp");
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "正在上传文件夹:" name;
}));
//新建文件夹
MakeDirectory(name);
//显示当前列表
GetDirList(name);
//添加
openFolder.Insert(0, name);
//目录下的文件列表
FileInfo[] files = info.GetFiles();
foreach (FileInfo file in files)
{
FileListInfo fli = new FileListInfo();
fli.大小 = file.Length.ToString();
fli.类型 = "文件";
fli.path = file.FullName;
fli.文件名称 = file.Name.Replace("#", "Sharp");
fli.年_时间 = file.CreationTime.ToString();
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "正在上传文件:" file.Name;
}));
//上传文件
UpLoadFile(fli);
}
//子目录
DirectoryInfo[] directoies = info.GetDirectories();
//递归添加
foreach (DirectoryInfo d in directoies)
{
ViewDirectory(d);
}
BackUp();
}
catch(Exception ee)
{
MessageBox.Show("上传时出现错误!--" ee.Message "\n\n目录:" info.FullName);
}
}
#endregion
#region 上传下载队列
/// <summary>
/// 上传下载队列
/// </summary>
/// <param name="fileinfor"></param>
private void DownUploadList(object fileinfor)
{
}
#endregion
#region 新建、删除文件夹 删除文件
/// <summary>
/// 删除文件
/// </summary>
/// <param name="filename">文件名称</param>
private void DeleteFile(string filename)
{
if (!GetFileDirList("文件").Contains(filename))
{
throw new Exception("该文件不存在!");
}
string url = GetFtpFpath(GetFilePath()) "/" filename;
FtpWebResponse fwp = open(url, WebRequestMethods.Ftp.DeleteFile);
fwp.GetResponseStream();
fwp.Close();
}
/// <summary>
/// 新建文件夹
/// </summary>
/// <param name="foldername">文件夹名称</param>
private void MakeDirectory(string foldername)
{
if (GetFileDirList("文件夹").Contains(foldername.ToLower()))
{
throw new Exception("该子目录已存在!");
}
string url = GetFtpFpath(GetFilePath()) "/" foldername;
FtpWebResponse frsp = open(url, WebRequestMethods.Ftp.MakeDirectory);
frsp.GetResponseStream();
frsp.Close();
}
/// <summary>
/// 删除文件夹
/// </summary>
/// <param name="foldername">文件夹名称</param>
private void RemoveDirectory(string foldername)
{
string url = GetFtpFpath(GetFilePath());
if (foldername.Trim() != "")
{
url = "/" foldername;
}
if (foldername.Trim() != "")
{
if (!GetFileDirList("文件夹").Contains(foldername.ToLower()))
{
throw new Exception("该子目录不存在!");
}
}
FtpWebResponse df = open(url, WebRequestMethods.Ftp.RemoveDirectory);
df.GetResponseStream();
df.Close();
}
/// <summary>
/// 删除文件夹以及子文件夹
/// </summary>
/// <param name="foldername">文件夹内容</param>
private void RemoveDirAll(string foldername)
{
try
{
openFolder.Insert(0, foldername);
GetDirList(foldername);
//获取该文件夹下面的文件
List<string> files = GetFileDirList("文件");
//删除文件
foreach (string ss in files)
{
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "正在删除文件:" ss;
}));
GetDirList(foldername);
DeleteFile(ss);
}
//获取文件夹
List<string> Directorys = GetFileDirList("文件夹");
if (Directorys.Count == 0)
{
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "正在删除文件夹:" foldername;
}));
RemoveDirectory("");
}
else
{
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "正在处理....";
}));
//文件夹里面有文件
foreach (string ss in Directorys)
{
RemoveDirAll(ss);
}
}
BackUp();
}
catch
{
}
}
/// <summary>
/// 开始删除
/// </summary>
/// <param name="foldername"></param>
private void StartRemove(object foldername)
{
string fanme = foldername.ToString();
RemoveDirAll(fanme);
try
{
Invoke((EventHandler)(delegate
{
tb_showstate.Text = "";
MessageBox.Show("删除完成!");
}));
}
catch { }
}
#endregion
评论