一个用winform开发的FTP上传、下载、删除文件的简单列子:

配套源码下载:https://download.csdn.net/download/djk8888/10473477

注释尽可能详尽,希望大家一看就会。

页面相关代码:

using System;
using System.Collections.Generic;
using System.IO;
using System.Text;
using System.Text.RegularExpressions;
using System.Windows.Forms;namespace winform_ftp
{public partial class Form1 : Form{public Form1(){InitializeComponent();}private void Form1_Load(object sender, EventArgs e){this.cmbFolder.Text = "默认文档";Bind();}//刷新private void btnRefresh_Click(object sender, EventArgs e){Bind();}private void Bind(){FileStream fs = new FileStream(Application.StartupPath + "\\db.txt", FileMode.Open);StreamReader sr = new StreamReader(fs, Encoding.Default);var jsonStr = sr.ReadToEnd();//取出json字符串sr.Close();fs.Close();List<FtpEntity> temp = new List<FtpEntity>();var dt = JsonHelper.JsonToObject(jsonStr.Trim(), temp);if (dt != null){this.dataGridView1.DataSource = dt;dataGridView1.Columns["ID"].Width = 50;dataGridView1.Columns["FileName"].Width = 150;dataGridView1.Columns["FileFullName"].Width = 300;dataGridView1.Columns["FileUrl"].Width = 150;}}//下载private void btnDownload_Click(object sender, EventArgs e){if (dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value != null){if ((bool)dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value == true){string FileFullName = dataGridView1.Rows[LastSelectRowIndex].Cells["FileFullName"].Value.ToString().Trim();string FileUrl = dataGridView1.Rows[LastSelectRowIndex].Cells["FileUrl"].Value.ToString().Trim();FolderBrowserDialog fbd = new FolderBrowserDialog();//文件选择框DialogResult dr = fbd.ShowDialog();//选择下载的路径if (dr == DialogResult.Cancel) return;string LocalDir = fbd.SelectedPath + "\\" + FileFullName;//本地保存文件路径+文件名fbd.Dispose();Application.DoEvents();try{var b = FtpHelper.Down(FileUrl, FileFullName, LocalDir);if (b == true){MessageBox.Show("文件:" + FileFullName + "下载成功!");foreach (DataGridViewRow dgvr in dataGridView1.Rows){dgvr.Cells["check"].Value = false;}}else{MessageBox.Show("文件下载失败!");}}catch (Exception ex){MessageBox.Show(ex.ToString());}}}}//上传private void btnUpload_Click(object sender, EventArgs e){//文件选择器OpenFileDialog ofd = new OpenFileDialog();ofd.Filter = "支持的文件格式(word,excel,pdf,文本,图片)|*.doc;*.docx;*.xls;*.xlsx;*.pdf;*.txt;*.jpg;*.jpeg;|Word文件(*.doc;*.docx)|*.doc;*.docx|Excel文件(*.xls;*.xlsx)|*.xls;*.xlsx|文本文件(*.txt)|*.txt|图片文件(*.jpg;*.jpeg)|*.jpg;*.jpeg";if (ofd.ShowDialog() == System.Windows.Forms.DialogResult.Cancel) return;string ofdLocalFileName = ofd.FileName;//文件本地路径ofd.Dispose();//判断是否选择文件FileInfo fi = new FileInfo(ofdLocalFileName);if (!fi.Exists){MessageBox.Show("请选择一个文件");return;}//判断文件格式if (!".doc.docx.xls.xlsx.pdf.txt.jpg.jpeg".Contains(fi.Extension.ToLower())){MessageBox.Show("不支持的文件格式");return;}//判断文件大小if (fi.Length > 1024 * 1024 * 1)//文件限制:1mb{MessageBox.Show("文件内容过大!请上传小于1mb的文件!");return;}//准备上传fi = new FileInfo(ofdLocalFileName);string FileName = Regex.Replace(fi.Name.Replace(fi.Extension, ""), "\\s+", "");FileName = FileName.Replace("#", "$");//文件名称(不含扩展名)(存数据库用于查询,如:文件名相同的,但类型不同的文件:文件1.txt、文件1.doc、文件1.jpg、文件1.pdf)string FileType = fi.Extension.ToLower().Trim();//文件扩展名(存数据库,用于分类)string FileFullName = FileName + "_" + DateTime.Now.ToString("yyyyMMddHHmmssfff") + fi.Extension.Trim();//文件完整名称(含扩展名,用于下载,重要!必须!)DateTime UploadTime = DateTime.Now;//上传时间(存数据库,用于查询)string FileDir = cmbFolder.Text + "/" + UploadTime.ToString("yyyyMMdd");//路径(文件夹+日期,重要!必须!)try{FtpHelper.CreateDirectory(cmbFolder.Text);//创建根文件夹(可自定义)}catch { }   //如果文件夹已存在,就跳过!try{FtpHelper.CreateDirectory(FileDir);//创建子文件夹(年月日期)}catch { }   //如果文件夹已存在,就跳过!FtpHelper.FileDir = FileDir;//上传路径var result = FtpHelper.Upload(FileFullName, ofdLocalFileName);//开始FTP上传文件!if (result == true)//上传成功后,写入数据库(sqlServer,mySql等等...){try{//此处,txt文件“db.txt”充当数据库文件,用于存放、读写、删除,json数据对象集合(即json字符串)FileStream fs = new FileStream(Application.StartupPath + "\\db.txt", FileMode.Open);StreamReader sr = new StreamReader(fs, Encoding.Default);var jsonStr = sr.ReadToEnd();List<FtpEntity> temp = new List<FtpEntity>();var dt = JsonHelper.JsonToObject(jsonStr.Trim(), temp);sr.Close();fs.Close();if (dt != null){List<FtpEntity> list = (List<FtpEntity>)dt;//object转List<T>FtpEntity entity = new FtpEntity();if (list != null && list.Count > 0){entity.ID = list[list.Count - 1].ID + 1;//新ID=原最大ID值+1}else{entity.ID = 1;}entity.FileFullName = FileFullName;entity.FileName = FileName;entity.FileType = FileType;entity.FileUrl = FileDir;entity.UploadTime = UploadTime;list.Add(entity);//数据集合添加一条新数据string json = JsonHelper.ObjectToJson(list);//list集合转json字符串StreamWriter sw = new StreamWriter(Application.StartupPath + "\\db.txt", false, System.Text.Encoding.UTF8);//参数2:false覆盖;true追加sw.WriteLine(json);//写入文件sw.Close();MessageBox.Show("上传成功!");Bind();//刷新列表}}catch (Exception ex){MessageBox.Show("文件上传成功!但写入数据库失败:\r\n" + ex.ToString());//请检查文件夹的读写权限}}else{MessageBox.Show("上传失败!");}}//列表单选int LastSelectRowIndex = default(int);private void dataGridView1_CellContentClick(object sender, DataGridViewCellEventArgs e){try{if (e.RowIndex >= 0){//选择的是checkBoxif (dataGridView1.Columns[e.ColumnIndex] is DataGridViewCheckBoxColumn){if (LastSelectRowIndex == e.RowIndex){return;}else{if (dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value != null){if ((bool)dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value){dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value = false;}}}LastSelectRowIndex = e.RowIndex;}}}catch{foreach (DataGridViewRow dgvr in dataGridView1.Rows){dgvr.Cells["check"].Value = false;}}}private void btnDelete_Click(object sender, EventArgs e){if (MessageBox.Show("确认删除?", "提示", MessageBoxButtons.YesNo, MessageBoxIcon.Question) == DialogResult.Yes){if (dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value != null){if ((bool)dataGridView1.Rows[LastSelectRowIndex].Cells[0].Value == true){string FileFullName = dataGridView1.Rows[LastSelectRowIndex].Cells["FileFullName"].Value.ToString().Trim();string FileUrl = dataGridView1.Rows[LastSelectRowIndex].Cells["FileUrl"].Value.ToString().Trim();string ID = dataGridView1.Rows[LastSelectRowIndex].Cells["ID"].Value.ToString().Trim();var b = FtpHelper.Delete(FileUrl, FileFullName);if (b){FileStream fs = new FileStream(Application.StartupPath + "\\db.txt", FileMode.Open);StreamReader sr = new StreamReader(fs, Encoding.Default);var jsonStr = sr.ReadToEnd();List<FtpEntity> Entity = new List<FtpEntity>();var dt = JsonHelper.JsonToObject(jsonStr.Trim(), Entity);sr.Close();fs.Close();List<FtpEntity> list = (List<FtpEntity>)dt;//object转List<T>FtpEntity delEntity = list.Find(a => a.ID == int.Parse(ID));//根据ID值取出对象list.Remove(delEntity);//从列表中删除此对象string json = JsonHelper.ObjectToJson(list);//将新的list转成json写入txtStreamWriter sw = new StreamWriter(Application.StartupPath + "\\db.txt", false, System.Text.Encoding.UTF8);//参数2:false覆盖;true追加sw.WriteLine(json);//写入文件sw.Close();MessageBox.Show("删除FTP上的文件成功!");Bind();}else{MessageBox.Show("删除FTP上的文件失败!");}}}}}}
}

FTP相关代码:

using System;
using System.IO;
using System.Net;namespace winform_ftp
{/// <summary>/// 请勿上传违法、违规等不和谐的文件!/// CSDN博客:https://blog.csdn.net/djk8888/// 腾讯微博:http://t.qq.com/djk8888/// </summary>public class FtpHelper{public static string FileDir { get; set; }public static string FtpHost = "ftp://013.3vftp.com/";//ftp地址(如果ftp测试空间满了,请登上ftp删掉点测试文件即可)public static string FtpUser = "djk8888csdn";//ftp账号(请勿上传违法、违规等不和谐的文件!)public static string FtpPassword = "123456";//ftp密码(别怀疑,就是:123456)//请勿上传违法、违规等不和谐的文件!重要的事说三遍!本人概不负责!/// <summary>/// FTP下载文件/// </summary>/// <param name="RemoteDir">FTP上的文件路径</param>/// <param name="RemoteFileName">完整文件名</param>/// <param name="LocalDir">下载到本地的路径</param>public static bool Down(string RemoteDir, string RemoteFileName, string LocalDir){try{FileStream outputStream = new FileStream(LocalDir, FileMode.Create, FileAccess.Write);//新建本地文件(空文件)outputStream.Close();//关闭IOreturn Download(RemoteDir, RemoteFileName, LocalDir);//将FTP上的文件内容写入到本地空文件中去}catch{return false;//新建本地文件失败}}private static bool Download(string RemoteDir, string RemoteFileName, string LocalDir){FtpWebRequest reqFTP;try{//①读取FTP上的文件FileStream outputStream = new FileStream(LocalDir, FileMode.Create);//建立FTP链接reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(FtpHost + RemoteDir + "/" + RemoteFileName));//读取FTP上的文件reqFTP.Method = WebRequestMethods.Ftp.DownloadFile;//FTP下载协议reqFTP.UseBinary = true;//指定文件传输类型reqFTP.Credentials = new NetworkCredential(FtpUser, FtpPassword);//FTP通信凭证(即登录ftp)FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();//登录成功//②将FTP上的文件内容转化成数据流Stream ftpStream = response.GetResponseStream();//将FTP上的文件转化为数据流              int bufferSize = 2048;//缓冲大小,单位byte               byte[] buffer = new byte[bufferSize];//数据包int readCount;//循环次数readCount = ftpStream.Read(buffer, 0, bufferSize);//计算循环次数//③将FTP文件内容写入到本地空文件中去while (readCount > 0){outputStream.Write(buffer, 0, readCount);//写入每一次读取的数据流readCount = ftpStream.Read(buffer, 0, bufferSize);//重新计算次数}//④关闭IOftpStream.Close();outputStream.Close();response.Close();return true;}catch //(Exception ex){return false;}}/// <summary>/// 创建文件夹/// </summary>/// <param name="RemoteDir">FTP上文件路径</param>/// <returns></returns>public static string CreateDirectory(string RemoteDir){FtpWebRequest request = SetFtpConfig(WebRequestMethods.Ftp.MakeDirectory, RemoteDir);FtpWebResponse response = (FtpWebResponse)request.GetResponse();return response.StatusDescription;}private static FtpWebRequest SetFtpConfig(string method, string RemoteDir){return SetFtpConfig(method, RemoteDir, "");}private static FtpWebRequest SetFtpConfig(string method, string RemoteDir, string RemoteFileName){RemoteDir = string.IsNullOrEmpty(RemoteDir) ? "" : RemoteDir.Trim();return SetFtpConfig(FtpHost, FtpUser, FtpPassword, method, RemoteDir, RemoteFileName);}private static FtpWebRequest SetFtpConfig(string host, string username, string password, string method, string RemoteDir, string RemoteFileName){System.Net.ServicePointManager.DefaultConnectionLimit = 50;FtpWebRequest request = (FtpWebRequest)WebRequest.Create(host + RemoteDir + "/" + RemoteFileName);request.Method = method;request.Credentials = new NetworkCredential(username, password);request.UsePassive = false;request.UseBinary = true;request.KeepAlive = false;return request;}/// <summary>/// FTP上传文件/// </summary>/// <param name="FileName">上传到FTP后的文件名</param>/// <param name="localFileName">本地选择的文件名</param>/// <param name="falsegz"></param>/// <returns></returns>public static bool Upload(string FileName, string localFileName){return Upload(FileDir, FileName, localFileName);}private static bool Upload(string FileDir, string FileName, string localFileName){try{//①在FTP上创建一个空文件:FtpWebRequest request = SetFtpConfig(WebRequestMethods.Ftp.UploadFile, FileDir, FileName);//创建空文件//②读取本地文件的内容,转化成流:FileStream fs = new FileStream(localFileName, FileMode.Open, FileAccess.Read);//打开本地文件int buffLength = 20480;//缓存大小,单位bytebyte[] buff = new byte[buffLength];//数据包var contentLen = fs.Read(buff, 0, buffLength);//每次读文件流的kb     //③将本地文件的内容,写入到FTP上空文件中去:Stream strm = request.GetRequestStream(); //把上传的文件写入本地文件的流                             while (contentLen != 0)//流内容没有结束,循环  {strm.Write(buff, 0, contentLen);// 把内容从file stream 写入upload stream  contentLen = fs.Read(buff, 0, buffLength);//读取流}//④关闭IOstrm.Close();fs.Close();return true;//返回成功}catch //(Exception ex){return false;}}/// <summary>  /// 删除文件  /// </summary>  /// <param name="FileDir">ftp文件路径(不包含文件名)</param>  /// <param name="FileName">文件名</param>  /// <returns>返回值</returns>  public static bool Delete(string FileDir, string FileName){bool success = false;FtpWebRequest ftpWebRequest = null;FtpWebResponse ftpWebResponse = null;Stream ftpResponseStream = null;StreamReader streamReader = null;try{string uri = FtpHost + FileDir + "/" + FileName;//例:ftp://013.3vftp.com/默认文档/20180608/文件1.txtftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));ftpWebRequest.Credentials = new NetworkCredential(FtpUser, FtpPassword);ftpWebRequest.KeepAlive = false;ftpWebRequest.Method = WebRequestMethods.Ftp.DeleteFile;ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();long size = ftpWebResponse.ContentLength;ftpResponseStream = ftpWebResponse.GetResponseStream();streamReader = new StreamReader(ftpResponseStream);string result = String.Empty;result = streamReader.ReadToEnd();success = true;}catch (Exception){success = false;}finally{if (streamReader != null){streamReader.Close();}if (ftpResponseStream != null){ftpResponseStream.Close();}if (ftpWebResponse != null){ftpWebResponse.Close();}}return success;}
/// <summary>/// 修改文件名/// </summary>public bool FileRename(string RemoteFileName, string newFileName){return FileRename(RemoteDir, RemoteFileName, newFileName);}private bool FileRename(string RemoteDir, string RemoteFileName, string newFileName){bool success = false;FtpWebRequest ftpWebRequest = null;FtpWebResponse ftpWebResponse = null;Stream ftpResponseStream = null;try{string uri = FtpHost + RemoteDir + "/" + RemoteFileName;//ftp上完整路径:ftp地址/文件夹/文件名.扩展名ftpWebRequest = (FtpWebRequest)FtpWebRequest.Create(new Uri(uri));ftpWebRequest.Credentials = new NetworkCredential(FtpUser, FtpPassword);ftpWebRequest.UseBinary = true;ftpWebRequest.Method = WebRequestMethods.Ftp.Rename;ftpWebRequest.RenameTo = newFileName;//新名称ftpWebResponse = (FtpWebResponse)ftpWebRequest.GetResponse();ftpResponseStream = ftpWebResponse.GetResponseStream();success = true;}catch (Exception){success = false;}finally{if (ftpResponseStream != null){ftpResponseStream.Close();}if (ftpWebResponse != null){ftpWebResponse.Close();}}return success;}}}

配套源码下载:https://download.csdn.net/download/djk8888/10473477

webForm的ftp上传下载:https://blog.csdn.net/djk8888/article/details/80736524

winform实现FTP上传、下载、删除文件(附源码下载)相关推荐

  1. JAVA文件上传详解(附源码)

    文章目录 JAVA文件上传详解(附源码) 1.准备工作 2.使用类介绍 FileItem类 ServletFileUpload类 3.代码编写 JAVA文件上传详解(附源码) 在web应用中,文件上传 ...

  2. springboot入门系列教程|第九篇:springboot实现图片上传与显示(附源码)

    前言## 上一篇我们介绍了springboot如何实现自定义拦截器配合注解使用,那么这篇我们将介绍springboot实现图片上传的功能. 目录## 文章目录 前言## 目录## 项目创建### 项目 ...

  3. [ASP.NET]web实现用FTP上传、下载文件(附源码)

    文章配套源码下载地址:https://download.csdn.net/download/djk8888/10486581 index.aspx 页: <%@ Page Language=&q ...

  4. Winforn中DevExpress的TreeList中显示某路径下的所有目录和文件(附源码下载)

    场景 Winform中DevExpress的TreeList的入门使用教程(附源码下载): https://blog.csdn.net/BADAO_LIUMANG_QIZHI/article/deta ...

  5. php 图片 投稿 源码,php图片上传,审核,显示源码(转载)

    php图片上传,审核,显示源码(转载) 最近想为http://gif.nbqq.net,加一个网友可以自主上传的页面,然后我审核.所以百度了下源码先.下午好好研究下. 首先来看下上传部分的表单代码: ...

  6. 《在(虚拟机)ubuntu16.04上进行openwrt环境搭建及源码下载》

    广西·河池学院 广西高校重点实验室培训基地 系统控制与信息处理重点实验室 本篇博客来之河池学院:OpenWrt无线路由组 写作时间: 2020年7月30日21:00:51 <在(虚拟机)ubun ...

  7. 小程序源码:最新掌上题库微信小程序源码下载,修复登录接口,支持在线考试,自定义导入考题-多玩法安装简单

    这是一款题库微信小程序源码 支持积分商城.自定义试题及导入.知识点分类.模式试题考试.流量主等 首页模块:专项刷题 .题型刷题.乱序刷题.我的收藏.我的错题.未作习题.刷知识点.考前必背 另外还有更多 ...

  8. 最新掌上题库微信小程序源码下载,修复登录接口,支持在线考试,自定义导入考题

    这是一款题库微信小程序源码 支持积分商城.自定义试题及导入.知识点分类.模式试题考试等 首页模块:专项刷题.题型刷题.乱序刷题.我的收藏.我的错题.未作习题.刷知识点.考前必背 另外还有更多功能就不一 ...

  9. html仿微信滑动删除,使用Vue实现移动端左滑删除效果附源码

    左滑删除在移动端是很常见的一种操作,常见于删除购物车中的商品,删除收藏夹中文章等等场景.我们只需要手指按住要删除的对象,然后轻轻向左滑动,便会出现删除按钮,然后点击删除按钮即可删除对象. 点击下载源码 ...

  10. 我搭建了一个随机「毒鸡汤」语录网站附源码下载

    小伙伴们注意:公众号的推送机制不再按照时间前后推送了,微信公众号信息流乱序.君哥建议大家把科技毒瘤君公众号置顶(设为星标⭐),以便第一时间看到推送,非常感谢~,方法如下图: 1 演示效果 ★ 遇到喜欢 ...

最新文章

  1. 【前沿技术】Facebook 硬件负责人,带摄像头的智能眼镜将在 10 年内成为常态
  2. 毕马威:2018全球科技创新报告(附PDF下载)
  3. 最近QQ联系我解决问题的郁闷
  4. Vmware将于2007年8月在杭州和南京举办虚拟化巡展
  5. Linux线程(五)
  6. 未雨绸缪:从软件测试到质量保证
  7. P5135-painting【组合数学】
  8. 关于Tensorflow安装opencv和pygame
  9. 插入公式_一个小工具,彻底帮你搞定在Markdown中插入公式的问题
  10. ReentrantLock 分析
  11. heartbeat 非联网安装(通过配置本地yum文件库安装heartbeat)
  12. Linux内存管理之vmalloc与low_memory
  13. HLSL Effect的vertex shader和pixel shader的参数传递
  14. 红帽发布 Ansible Tower 3.4:在混合云中实践DevOps更便捷
  15. android框架揭秘之android中c++写的服务笔记
  16. 网易云音乐转码_网易云音乐产品分析报告
  17. 广播前置放大器的作用_前置放大器的作用和特点
  18. 二维离散傅里叶变换最详手算
  19. python爬取丁香园的疫情数据绘制Echarts地图
  20. Chemdraw —— SMILES与二维结构之间的互相转换

热门文章

  1. 2021南昌高考成绩什么时间段可以查询,2021年江西高考成绩几号可以查?江西高考成绩排名分数什么时候出...
  2. 创意电子学小知识:安培
  3. 「CSS深度指北」前端知识梳理之CSS篇(中秋国庆特别篇)
  4. 福州茉莉花茶企第三次在京亮相 茉莉花香获赞美
  5. 15 幼儿园分班问题
  6. 华为p60pro和p60art区别 华为p60pro和p60art对比
  7. Ubuntu根目录终极清理
  8. python分数运算_在Python中计算BLEU分数
  9. 汉化IDEA的方法 IntelliJ IDEA Community Edition
  10. eBay买家号养号攻略