public class FtpHelper
{
public FtpHelper(string p_url, string p_user, string p_password)
{
if (!p_url.ToUpper().StartsWith("FTP:"))
{
Url = "ftp://" + p_url;
}
else
{
Url = p_url;
}
User = p_user;
Password = p_password;
} public string Url { get; private set; } public string User { get; private set; } public string Password { get; private set; } public FtpWebRequest CreateConnect(string p_uri)
{
FtpWebRequest reqFTP; // 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)WebRequest.Create(new Uri(p_uri)); // ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(User, Password); return reqFTP;
} /// <summary>
/// 上传文件
/// </summary>
/// <param name="p_uri">ftp地址 ex=ftp://192.168.100.5//tmp// 切记要以//结尾</param>
/// <param name="p_filename">文件路径地址绝对路径 ex:C:\\Users\ligl\\Desktop\\1.txt</param>
/// <param name="isDelete"></param>
/// <returns></returns>
public bool Upload(string p_uri, string p_filename, bool isDelete = false)
{
var fileInf = new FileInfo(p_filename);
string uri = Path.Combine(p_uri, fileInf.Name); FtpWebRequest reqFTP = CreateConnect(uri);
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false; // 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.UploadFile; // 指定数据传输类型
reqFTP.UseBinary = true; // 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length + ; // 缓冲大小设置为2kb
int buffLength = ; var buff = new byte[buffLength];
int contentLen; // 打开一个文件流 (System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream(); // 每次读文件流的2kb
contentLen = fs.Read(buff, , buffLength); // 流内容没有结束
while (contentLen != )
{
// 把内容从file stream 写入 upload stream
strm.Write(buff, , contentLen); contentLen = fs.Read(buff, , buffLength);
} // 关闭两个流
strm.Close();
fs.Close(); var uploadResponse = (FtpWebResponse)reqFTP.GetResponse();
if (File.Exists(p_filename) && isDelete)
{
File.Delete(p_filename);
}
return (uploadResponse.StatusDescription.StartsWith(""));
}
catch (Exception ex)
{
//System.Windows.MessageBox.Show(ex.Message, "Upload Error");
throw ex;
}
} public bool Delete(string p_filename)
{
var fileInf = new FileInfo(p_filename);
string uri = Path.Combine(Url, fileInf.Name); try
{
var listRequest = (FtpWebRequest)WebRequest.Create(new Uri(uri)); listRequest.Method = WebRequestMethods.Ftp.DeleteFile; listRequest.Credentials = new NetworkCredential(User, Password); var listResponse = (FtpWebResponse)listRequest.GetResponse(); return (listResponse.StatusDescription.StartsWith(""));
}
catch (Exception ex)
{
throw ex;
}
} public bool MakeDir(string p_uri)
{
try
{
string url = Url;
if (string.IsNullOrEmpty(url))
{
return false;
} char lastChar = url[url.Length - ];
if (lastChar != '\\' && lastChar != '/')
{
url += '\\';
} string dir = p_uri.Remove(, url.Length); string[] dirs = dir.Split(new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries); dir = CreateDir(dirs); return CreateMackDir(url, dir);
}
catch (Exception ex)
{
throw ex;
}
} public string CreateDir(string[] p_dirNames)
{
var sb = new StringBuilder(); foreach (string dir in p_dirNames)
{
sb.Append(dir);
sb.Append("\\");
} return sb.ToString();
} public string GetFirstDir(string p_dir)
{
string[] dirs = p_dir.Split(new[] { Path.AltDirectorySeparatorChar, Path.DirectorySeparatorChar },
StringSplitOptions.RemoveEmptyEntries); if (dirs.Length > )
{
return dirs[];
} return string.Empty;
} public string RemvoeDirFromFirst(string p_longDir, string p_firstDir)
{
string value = p_longDir.Remove(, p_firstDir.Length + ); return value;
} private bool CreateMackDir(string p_url, string p_dir)
{
string dir = GetFirstDir(p_dir); if (string.IsNullOrEmpty(dir))
{
return true;
} string newurl = Path.Combine(p_url, dir);
if (!IsExsit(p_url, dir))
{
try
{
FtpWebRequest reqFtp = CreateConnect(newurl);
reqFtp.Method = WebRequestMethods.Ftp.MakeDirectory;
var response = (FtpWebResponse)reqFtp.GetResponse();
response.Close();
}
catch (Exception ex)
{
throw ex;
}
} string newdir = RemvoeDirFromFirst(p_dir, dir);
CreateMackDir(newurl, newdir); return true;
} public bool IsExsit(string p_url, string p_dir)
{
string[] list = GetFileList(p_url, WebRequestMethods.Ftp.ListDirectory); if (list == null || list.Length == )
{
return false;
} return list.Contains(p_dir);
} private string[] GetFileList(string path, string WRMethods) //上面的代码示例了如何从ftp服务器上获得文件列表
{
var result = new StringBuilder(); try
{
string tempPath = path;
if (!path.EndsWith("/"))
{
tempPath += "/";
} FtpWebRequest reqFtp = CreateConnect(tempPath);
reqFtp.Method = WRMethods;
WebResponse response = reqFtp.GetResponse();
var reader = new StreamReader(response.GetResponseStream(), Encoding.UTF8); //中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '/n'
if (result.Length > )
{
result.Remove(result.ToString().LastIndexOf('\n'), );
}
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
throw ex;
}
}
}

C# FTP上传的更多相关文章

  1. .net FTP上传文件

    FTP上传文件代码实现: private void UploadFileByWebClient() { WebClient webClient = new WebClient(); webClient ...

  2. 通过cmd完成FTP上传文件操作

    一直使用 FileZilla 这个工具进行相关的 FTP 操作,而在某一次版本升级之后,发现不太好用了,连接老是掉,再后来完全连接不上去. 改用了一段时间的 Web 版的 FTP 工具,后来那个页面也 ...

  3. FTP上传文件到服务器

    一.初始化上传控件. 1.我们这里用dropzone.js作为上传控件,下载地址http://www.dropzonejs.com/ 2.这里我们使用一个div元素作为dropzone载体. < ...

  4. 再看ftp上传文件

    前言 去年在项目中用到ftp上传文件,用FtpWebRequest和FtpWebResponse封装一个帮助类,这个在网上能找到很多,前台使用Uploadify控件,然后在服务器上搭建Ftp服务器,在 ...

  5. 【完整靠谱版】结合公司项目,仔细总结自己使用百度编辑器实现FTP上传的完整过程

    说在前面 工作中会遇到很多需要使用富文本编辑器的地方,比如我现在发布这篇文章离不开这个神器,而且现在网上编辑器太多了.记得之前,由于工作需要自己封装过一个编辑器的公共插件,是用ckeditor改版的, ...

  6. FTP上传文件提示550错误原因分析。

    今天测试FTP上传文件功能,同样的代码从自己的Demo移到正式的代码中,不能实现功能,并报 Stream rs = ftp.GetRequestStream()提示远程服务器返回错误: (550) 文 ...

  7. JAVA 实现FTP上传下载(sun.net.ftp.FtpClient)

    package com.why.ftp; import java.io.DataInputStream; import java.io.File; import java.io.FileInputSt ...

  8. FTP上传-封装工具类

    import java.io.File; import java.io.FileInputStream; import java.io.FileNotFoundException; import ja ...

  9. 记一次FTP上传文件总是超时的解决过程

    好久没写博,还是重拾记录一下吧. 背景:买了一个阿里云的云虚拟机用来搭建网站(起初不了解云虚拟主机和云服务器的区别,以为都是有SSH功能的,后来发现不是这样样子啊,云虚拟机就是FTP上传网页+MySQ ...

  10. FlashFXP(强大的FXP/ftp上传工具)V5.0.0.3722简体中文特别版

    flashfxp是功能强大的fxp/ftp软件,融合了一些其他优秀ftp软件的优点,如像cuteftp一样可以比较文件夹, FlashFXP是一款功能强大的FXP/ftp上传工具, FlashFXP集 ...

随机推荐

  1. 微信网站设置右上角发送、分享的内容——.net版本

    一.首先了解本文要解决的问题: 公司前一段开发了移动网站,老板喜欢通过微信看,然后把看到的东西通过右上角的按钮分享出来,但老板发现分享出来的东西,没有指定的图片,没有描述:所以我就得老老实实干活了.. ...

  2. MySql安装与MySQL添加用户、删除用户与授权

    1.安装MySql       目前MySQL有两种形式的文件,一个是msi格式,一个是zip格式的.msi格式的直接点击setup.exe就好,按照步骤进行.但是很多人下了zip格式的解压发现没有s ...

  3. C++/CLI——读书笔记《Visual C++/CLI从入门到精通》 第Ⅳ部分

    =================================版权声明================================= 版权声明:本文为博主原创文章 未经许可不得转载  请通过右 ...

  4. Centos和Redhat的区别和联系

    网上看到的,转载给大家 CentOS与RedHat的关系: RedHat在发行的时候,有两种方式:二进制的发行方式以及源代码的发行方式.无论是哪一种发行方式,你都可以免费获得(例如从网上下载),并再次 ...

  5. Javascript进度条

    一个简单的进度条演示. <!doctype html> <html> <head> <meta charset="utf8"> &l ...

  6. 系统进程 zygote(二)—— zygote.rc 脚本

    夕阳已在沉沉的淡化,这黄昏的美,有谁能描画?莽莽的天涯,哪里是我的家,哪里是我的家?爱人呀,我这般的想着你,你那里可也有丝毫的牵挂?—— 徐志摩·海边的梦 ilocker:关注 Android 安全( ...

  7. 微信公众平台C# SDK:Senparc.Weixin.MP.dll

    https://github.com/Senparc/WeiXinMPSDK [转] http://www.cnblogs.com/szw/archive/2013/01/13/senparc-wei ...

  8. 有评论就是我最大的动力~MySQL基础篇完结(存储引擎和图形化管理工具)

    hi 今天登上来,发现竟然有了3个评论~~加油吧! 这周的计划其实远远没有达到,然后下周还有一大堆事情...那么...周末好好玩吧~ 今天试图完结MySQL的基础篇知识,小白变为大白? 1.MySQL ...

  9. 用PS制作时尚美观的LOGO

    今日,在网上看到一篇帖子,介绍了各种时尚美观的六边形LOGO,其中一个吸引了我的目光. 一时技痒,尝试着用PS把它临摹出来 1.新建文档,大小600*600 2.用多边形工具,边数选择6,按住Shif ...

  10. 我的Github之旅(一)

    第一站:本地环境中的Github配置 1.参考链接 作为初学者,需要了解的有[本地环境中的github配置(基于mac)][1],以及git知识,这里推荐一个网站[猴子都能懂的Git入门][2],最后 ...