一个用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 temp = new List();
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 temp = new List();
var dt = JsonHelper.JsonToObject(jsonStr.Trim(), temp);
sr.Close();
fs.Close();
if (dt != null)
{
List list = (List)dt;//object转List
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)
{
//选择的是checkBox
if (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 Entity = new List();
var dt = JsonHelper.JsonToObject(jsonStr.Trim(), Entity);
sr.Close();
fs.Close();
List list = (List)dt;//object转List
FtpEntity delEntity = list.Find(a => a.ID == int.Parse(ID));//根据ID值取出对象
list.Remove(delEntity);//从列表中删除此对象
string json = JsonHelper.ObjectToJson(list);//将新的list转成json写入txt
StreamWriter 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
{
///
/// 请勿上传违法、违规等不和谐的文件!
/// CSDN博客:https://blog.csdn.net/djk8888
/// 腾讯微博:http://t.qq.com/djk8888
///
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)
//请勿上传违法、违规等不和谐的文件!重要的事说三遍!本人概不负责!
///
/// FTP下载文件
///
/// FTP上的文件路径
/// 完整文件名
/// 下载到本地的路径
public static bool Down(string RemoteDir, string RemoteFileName, string LocalDir)
{
try
{
FileStream outputStream = new FileStream(LocalDir, FileMode.Create, FileAccess.Write);//新建本地文件(空文件)
outputStream.Close();//关闭IO
return 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);//重新计算次数
}
//④关闭IO
ftpStream.Close();
outputStream.Close();
response.Close();
return true;
}
catch //(Exception ex)
{
return false;
}
}
///
/// 创建文件夹
///
/// FTP上文件路径
///
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;
}
///
/// FTP上传文件
///
/// 上传到FTP后的文件名
/// 本地选择的文件名
///
///
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;//缓存大小,单位byte
byte[] 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);//读取流
}
//④关闭IO
strm.Close();
fs.Close();
return true;//返回成功
}
catch //(Exception ex)
{
return false;
}
}
///
/// 删除文件
///
/// ftp文件路径(不包含文件名)
/// 文件名
/// 返回值
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.txt
ftpWebRequest = (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;
}
///
/// 修改文件名
///
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