本来这篇博文应该在上周就完成的,可无奈,最近工作比较忙,没有时间写,所以推迟到了今天。可悲的是,今天也没有太多的时间,所以决定给大家贴出源码,不做详细的分析说明,如果有不懂的,可以给我留言,我们共同讨论。

using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Security.Cryptography;
using System.Text;
using System.Windows.Forms; namespace UpLoad
{
class UpLoadFiles
{
private static string FTPCONSTR = "";//FTP的服务器地址,格式为ftp://192.168.1.234:8021/。ip地址和端口换成自己的,这些建议写在配置文件中,方便修改
private static string FTPUSERNAME = "";//FTP服务器的用户名
private static string FTPPASSWORD = "";//FTP服务器的密码 #region 本地文件上传到FTP服务器
/// <summary>
/// 上传文件到远程ftp
/// </summary>
/// <param name="path">本地的文件目录</param>
/// <param name="name">文件名称</param>
/// <returns></returns>
public static bool UploadFile(string path, string name)
{
string erroinfo = "";
FileInfo f = new FileInfo(path);
path = path.Replace("\\", "/");
path = FTPCONSTR + "/data/uploadFile/photo/" + name;//这个路径是我要传到ftp目录下的这个目录下
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
erroinfo = "完成";
return true;
}
catch (Exception ex)
{
erroinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
} /// <summary>
/// 上传文件到远程ftp
/// </summary>
/// <param name="ftpPath">ftp上的文件路径</param>
/// <param name="path">本地的文件目录</param>
/// <param name="id">文件名</param>
/// <returns></returns>
public static bool UploadFile(string ftpPath, string path, string id)
{
string erroinfo = "";
FileInfo f = new FileInfo(path);
path = path.Replace("\\", "/");
bool b = MakeDir(ftpPath);
if (b == false)
{
return false;
}
path = FTPCONSTR + ftpPath + id;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
strm.Close();
fs.Close();
erroinfo = "完成";
return true;
}
catch (Exception ex)
{
erroinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
/// <summary>
/// 上传
/// </summary>
/// <param name="path">本地的文件目录</param>
/// <param name="name">文件名称</param>
/// <param name="pb">进度条</param>
/// <returns></returns>
public static bool UploadFile(string path, string name, ProgressBar pb)
{
string erroinfo = "";
float percent = 0;
FileInfo f = new FileInfo(path);
path = path.Replace("\\", "/");
path = FTPCONSTR + "/data/uploadFile/photo/" + name;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
int allbye = (int)f.Length;
if (pb != null)
{
pb.Maximum = (int)allbye; }
int startbye = 0;
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
startbye = contentLen + startbye;
if (pb != null)
{
pb.Value = (int)startbye;
}
contentLen = fs.Read(buff, 0, buffLength);
percent = (float)startbye / (float)allbye * 100;
}
strm.Close();
fs.Close();
erroinfo = "完成";
return true;
}
catch (Exception ex)
{
erroinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
/// <summary>
/// 文件上传到ftp
/// </summary>
/// <param name="ftpPath">ftp的文件路径</param>
/// <param name="path">本地的文件目录</param>
/// <param name="name">文件名称</param>
/// <param name="pb">进度条</param>
/// <returns></returns>
public static bool UploadFile(string ftpPath, string path, string name, ProgressBar pb)
{
//path = "ftp://" + UserUtil.serverip + path;
string erroinfo = "";
float percent = 0;
FileInfo f = new FileInfo(path);
path = path.Replace("\\", "/");
bool b = MakeDir(ftpPath);
if (b == false)
{
return false;
}
path = FTPCONSTR + ftpPath + name;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.UploadFile;
reqFtp.ContentLength = f.Length;
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
FileStream fs = f.OpenRead();
int allbye = (int)f.Length;
//if (pb != null)
//{
// pb.Maximum = (int)allbye; //}
int startbye = 0;
try
{
Stream strm = reqFtp.GetRequestStream();
contentLen = fs.Read(buff, 0, buffLength);
while (contentLen != 0)
{
strm.Write(buff, 0, contentLen);
startbye = contentLen + startbye;
percent = (float)startbye / (float)allbye * 100;
if (percent <= 100)
{
int i = (int)percent;
if (pb != null)
{
pb.BeginInvoke(new updateui(upui), new object[] { allbye, i, pb });
}
} contentLen = fs.Read(buff, 0, buffLength); // Console.WriteLine(percent);
}
strm.Close();
fs.Close();
erroinfo = "完成";
return true;
}
catch (Exception ex)
{
erroinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
private delegate void updateui(long rowCount, int i, ProgressBar PB);
public static void upui(long rowCount, int i, ProgressBar PB)
{
try
{
PB.Value = i;
}
catch { }
}
////上面的代码实现了从ftp服务器下载文件的功能
public static Stream Download(string ftpfilepath)
{
Stream ftpStream = null;
FtpWebResponse response = null;
try
{
ftpfilepath = ftpfilepath.Replace("\\", "/");
string url = FTPCONSTR + ftpfilepath;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
response = (FtpWebResponse)reqFtp.GetResponse();
ftpStream = response.GetResponseStream();
}
catch (Exception ee)
{
if (response != null)
{
response.Close();
}
MessageBox.Show("文件读取出错,请确认FTP服务器服务开启并存在该文件");
}
return ftpStream;
}
#endregion #region 从ftp服务器下载文件 /// <summary>
/// 从ftp服务器下载文件的功能
/// </summary>
/// <param name="ftpfilepath">ftp下载的地址</param>
/// <param name="filePath">存放到本地的路径</param>
/// <param name="fileName">保存的文件名称</param>
/// <returns></returns>
public static bool Download(string ftpfilepath, string filePath, string fileName)
{
try
{
filePath = filePath.Replace("我的电脑\\", "");
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + onlyFileName;
if (File.Exists(newFileName))
{
//errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
File.Delete(newFileName);
//return false;
}
ftpfilepath = ftpfilepath.Replace("\\", "/");
string url = FTPCONSTR + ftpfilepath;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
Stream ftpStream = response.GetResponseStream();
long cl = response.ContentLength;
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
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();
return true;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
//
/// <summary>
/// 从ftp服务器下载文件的功能----带进度条
/// </summary>
/// <param name="ftpfilepath">ftp下载的地址</param>
/// <param name="filePath">保存本地的地址</param>
/// <param name="fileName">保存的名字</param>
/// <param name="pb">进度条引用</param>
/// <returns></returns>
public static bool Download(string ftpfilepath, string filePath, string fileName, ProgressBar pb)
{
FtpWebRequest reqFtp = null;
FtpWebResponse response = null;
Stream ftpStream = null;
FileStream outputStream = null;
try
{
filePath = filePath.Replace("我的电脑\\", "");
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + onlyFileName;
if (File.Exists(newFileName))
{
try
{
File.Delete(newFileName);
}
catch { } }
ftpfilepath = ftpfilepath.Replace("\\", "/");
string url = FTPCONSTR + ftpfilepath;
reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
response = (FtpWebResponse)reqFtp.GetResponse();
ftpStream = response.GetResponseStream();
long cl = GetFileSize(url);
int bufferSize = 2048;
int readCount;
byte[] buffer = new byte[bufferSize];
readCount = ftpStream.Read(buffer, 0, bufferSize);
outputStream = new FileStream(newFileName, FileMode.Create); float percent = 0;
while (readCount > 0)
{
outputStream.Write(buffer, 0, readCount);
readCount = ftpStream.Read(buffer, 0, bufferSize);
percent = (float)outputStream.Length / (float)cl * 100;
if (percent <= 100)
{
if (pb != null)
{
pb.Invoke(new updateui(upui), new object[] { cl, (int)percent, pb });
}
}
// pb.Invoke(new updateui(upui), new object[] { cl, outputStream.Length, pb }); } //MessageBoxEx.Show("Download0");
return true;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
//MessageBoxEx.Show("Download00");
return false;
}
finally
{
//MessageBoxEx.Show("Download2");
if (reqFtp != null)
{
reqFtp.Abort();
}
if (response != null)
{
response.Close();
}
if (ftpStream != null)
{
ftpStream.Close();
}
if (outputStream != null)
{
outputStream.Close();
}
}
}
#endregion #region 获得文件的大小
/// <summary>
/// 获得文件大小
/// </summary>
/// <param name="url">FTP文件的完全路径</param>
/// <returns></returns>
public static long GetFileSize(string url)
{ long fileSize = 0;
try
{
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.Method = WebRequestMethods.Ftp.GetFileSize;
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
fileSize = response.ContentLength; response.Close();
}
catch (Exception ex)
{
MessageBox.Show(ex.Message);
}
return fileSize;
}
#endregion #region 在ftp服务器上创建文件目录 /// <summary>
///在ftp服务器上创建文件目录
/// </summary>
/// <param name="dirName">文件目录</param>
/// <returns></returns>
public static bool MakeDir(string dirName)
{
try
{
bool b = RemoteFtpDirExists(dirName);
if (b)
{
return true;
}
string url = FTPCONSTR + dirName;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
// reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
} }
/// <summary>
/// 判断ftp上的文件目录是否存在
/// </summary>
/// <param name="path"></param>
/// <returns></returns>
public static bool RemoteFtpDirExists(string path)
{ path = FTPCONSTR + path;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
reqFtp.UseBinary = true;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
reqFtp.Method = WebRequestMethods.Ftp.ListDirectory;
FtpWebResponse resFtp = null;
try
{
resFtp = (FtpWebResponse)reqFtp.GetResponse();
FtpStatusCode code = resFtp.StatusCode;//OpeningData
resFtp.Close();
return true;
}
catch
{
if (resFtp != null)
{
resFtp.Close();
}
return false;
}
}
#endregion #region 从ftp服务器删除文件的功能
/// <summary>
/// 从ftp服务器删除文件的功能
/// </summary>
/// <param name="fileName"></param>
/// <returns></returns>
public static bool DeleteFile(string fileName)
{
try
{
string url = FTPCONSTR + fileName;
FtpWebRequest reqFtp = (FtpWebRequest)FtpWebRequest.Create(new Uri(url));
reqFtp.UseBinary = true;
reqFtp.KeepAlive = false;
reqFtp.Method = WebRequestMethods.Ftp.DeleteFile;
reqFtp.Credentials = new NetworkCredential(FTPUSERNAME, FTPPASSWORD);
FtpWebResponse response = (FtpWebResponse)reqFtp.GetResponse();
response.Close();
return true;
}
catch (Exception ex)
{
//errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
#endregion
}
}

  这是从FTP文件上传、下载、新建目录以及删除文件的一个类,应该有用的到的地放。关于ftp的配置,如果大家有疑问的话可以去网上查查,如果后期我有时间的话我也会写一写。

C#实现FTP文件的上传、下载功能、新建目录以及文件的删除的更多相关文章

  1. 在Window的IIS中创建FTP的Site并用C#进行文件的上传下载

    文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服务器计算机上. 然后,远程计算机可以使用 FTP ...

  2. 创建FTP的Site并用C#进行文件的上传下载

    创建FTP的Site并用C#进行文件的上传下载 文件传输协议 (FTP) 是一个标准协议,可用来通过 Internet 将文件从一台计算机移到另一台计算机. 这些文件存储在运行 FTP 服务器软件的服 ...

  3. python使用ftplib模块实现FTP文件的上传下载

    python已经默认安装了ftplib模块,用其中的FTP类可以实现FTP文件的上传下载 FTP文件上传下载 # coding:utf8 from ftplib import FTP def uplo ...

  4. JavaWeb实现文件上传下载功能实例解析

    转:http://www.cnblogs.com/xdp-gacl/p/4200090.html JavaWeb实现文件上传下载功能实例解析 在Web应用系统开发中,文件上传和下载功能是非常常用的功能 ...

  5. JavaWeb 之文件的上传下载

    又到了每周更新博客的时候了,每看到自己发布的随笔阅读量上涨的时候就特别开心,我也会尽自己的努力提高自己的水平,总结出通俗易读的学习笔记,还望大家能多多支持!!! ------------------- ...

  6. 文件一键上传、汉字转拼音、excel文件上传下载功能模块的实现

    ----------------------------------------------------------------------------------------------[版权申明: ...

  7. linux链接及文件互相上传下载

    若排版紊乱可查看我的个人博客原文地址 基本操作 本篇博客主要介绍如何去链接远程的linux主机及如何实现本地与远程主机之间文件的上传下载操作,下面的linux系统是CentOS6.6 链接远程linu ...

  8. Spring实现文件的上传下载

    背景:之前一直做的是数据库的增删改查工作,对于文件的上传下载比较排斥,今天研究了下具体的实现,发现其实是很简单.此处不仅要实现单文件的上传,还要实现多文件的上传. 单文件的下载知道了,多文件的下载呢? ...

  9. SocketIo+SpringMvc实现文件的上传下载

    SocketIo+SpringMvc实现文件的上传下载 socketIo不仅可以用来做聊天工具,也可以实现局域网(当然你如果有外网也可用外网)内实现文件的上传和下载,下面是代码的效果演示: GIT地址 ...

  10. JAVAWEB之文件的上传下载

    文件上传下载 文件上传: 本篇文章使用的文件上传的例子使用的都是原生技术,servelt+jdbc+fileupload插件,这也是笔者的习惯,当接触到某些从未接触过的东西时,总是喜欢用最原始的东西将 ...

随机推荐

  1. Django之ORM使用以及模板语言

    一.ORM版增删改查 1.ORM的语句 1.类名.objects.all()          --> 返回一个列表 2.类名.objects.filter()       --> 返回一 ...

  2. php页面的基本语法

    概述: 1. PHP 脚本在服务器上执行,然后将纯 HTML 结果发送回浏览器. 2. PHP 脚本以 <?php 开始,以 ?> 结束,可以放到文档中的任何位置. 3. 当 PHP 解析 ...

  3. 关于jni调用报UnsatisfiedLinkError的可能

    一.说明 最近在做一个项目,需要使用java去调本地动态连接库,之前做测试的时候直接用pojo进行测试,是能够正常调用的.后面项目需要将接口封装为REST api,所以在spring boot上面开发 ...

  4. dede添加自定义函数

    在dede安装目录下的include/extend.func.php添加自定义函数: /** * 获取文章第一张图片 */ function getFirstImg($arcId) { global ...

  5. 品味性能之道<十>:Oracle Hint

    Hint 是Oracle 提供的一种SQL语法,它允许用户在SQL语句中插入相关的语法,从而影响SQL的执行方式. 因为Hint的特殊作用,所以对于开发人员不应该在代码中使用它,Hint 更像是Ora ...

  6. glog日志

    google 开源日志库 #include <glog/logging.h> yum install glog

  7. 项目 solrcloud / zookeeper 搭建

    财经道网站搜索引擎,数据快速检索,数据集群 功能描述:使用solr为项目数据库表p2p,银行理财,基金,贷款,信托,保险等建立数据索引,实现数据的导入,增量索引.实现检索建议和数据的快速查找.使用zo ...

  8. win7 一切软件都安装不上 解决 把他卸掉

    KB2962872   控制面板,添加删除程序,查看已更新

  9. 如果程序集是从 Web 上下载的,即使它存储于本地计算机,Windows 也会将其标记为 Web 文件,http://go.microsoft.com/fwlink/?LinkId=179545

    使用Silverlight,经常弄出很多莫名的XXX文件来于Web,神马信任程序集,就Build个程序都那么麻烦,应该在所有发布时注明一些最基本的配置说明,最BT莫过于连下载程序集的地方都找不到. 若 ...

  10. 2018.09.16 codeforces1041C. Coffee Break(双端队列)

    传送门 真心sb题啊. 考场上最开始看成了一道写过的原题... 仔细想了一会发现看错了. 其实就是一个sb队列. 每次插入到队首去就行了. 代码: #include<bits/stdc++.h& ...