using System;
using System.Collections.Generic;
using System.IO;
using System.Linq;
using System.Net;
using System.Text;
using System.Web;

namespace FTPHelper
{
//本文由MosCMS贡献
public class FTP_Class
{
private string ftpServerIP;
private string ftpUserID;
private string ftpPassword;
FtpWebRequest reqFTP;
public void Connecttest(string ftpServerIP, string ftpUserId, string ftppassword)
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri("ftp://" + ftpServerIP));
// 指定数据传输类型
reqFTP.UseBinary = true;
ftpUserID = ftpUserId;
ftpPassword = ftppassword;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);

}
#region 连接
private void Connect(String path)//连接ftp
{
// 根据uri创建FtpWebRequest对象
reqFTP = (FtpWebRequest)FtpWebRequest.Create(new Uri(path));
// 指定数据传输类型
reqFTP.UseBinary = true;
// ftp用户名和密码
reqFTP.Credentials = new NetworkCredential(ftpUserID, ftpPassword);
}
#endregion
#region ftp登录信息
public void FtpUpDown(string ftpServerIP, string ftpUserID, string ftpPassword)
{
this.ftpServerIP = ftpServerIP;
this.ftpUserID = ftpUserID;
this.ftpPassword = ftpPassword;
}
#endregion
#region 获取文件列表

/// 获取文件列表
private string[] GetFileList(string path, string WRMethods)//上面的代码示例了如何从ftp服务器上获得文件列表
{
string[] downloadFiles;
StringBuilder result = new StringBuilder();
try
{
Connect(path);
reqFTP.Method = WRMethods;
WebResponse response = reqFTP.GetResponse();
StreamReader reader = new StreamReader(response.GetResponseStream(), System.Text.Encoding.UTF8);//中文文件名
string line = reader.ReadLine();
while (line != null)
{
result.Append(line);
result.Append("\n");
line = reader.ReadLine();
}
// to remove the trailing '\n'
result.Remove(result.ToString().LastIndexOf('\n'), 1);
reader.Close();
response.Close();
return result.ToString().Split('\n');
}
catch (Exception ex)
{
System.Windows.Forms.MessageBox.Show(ex.Message);
downloadFiles = null;
return downloadFiles;
}
}
public string[] GetFileList(string path)//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/" + path, WebRequestMethods.Ftp.ListDirectory);
}
public string[] GetFileList()//上面的代码示例了如何从ftp服务器上获得文件列表
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectory);
}
#endregion

#region 上传文件
public bool Upload(string filename, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能
{
path = path.Replace("\\", "/");
FileInfo fileInf = new FileInfo(filename);
string uri = "ftp://" + path + "/" + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令

reqFTP.Method = WebRequestMethods.Ftp.UploadFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流
strm.Close();
fs.Close();
errorinfo = "完成";
return true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
#endregion
#region 续传文件
public bool Upload(string filename, long size, string path, out string errorinfo) //上面的代码实现了从ftp服务器上载文件的功能
{
path = path.Replace("\\", "/");
FileInfo fileInf = new FileInfo(filename);
//string uri = "ftp://" + path + "/" + fileInf.Name;
string uri = "ftp://" + path;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.AppendFile;
// 上传文件时通知服务器文件的大小
reqFTP.ContentLength = fileInf.Length;
// 缓冲大小设置为kb
int buffLength = 2048;
byte[] buff = new byte[buffLength];
int contentLen;
// 打开一个文件流(System.IO.FileStream) 去读上传的文件
FileStream fs = fileInf.OpenRead();
try
{
StreamReader dsad = new StreamReader(fs);
fs.Seek(size, SeekOrigin.Begin);
// 把上传的文件写入流
Stream strm = reqFTP.GetRequestStream();
// 每次读文件流的kb
contentLen = fs.Read(buff, 0, buffLength);
// 流内容没有结束
while (contentLen != 0)
{
// 把内容从file stream 写入upload stream
strm.Write(buff, 0, contentLen);
contentLen = fs.Read(buff, 0, buffLength);
}
// 关闭两个流

strm.Close();
fs.Close();
errorinfo = "完成";
return true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法完成上传", ex.Message);
return false;
}
}
#endregion
#region 下载文件
public bool Download(string ftpfilepath, string filePath, string fileName, out string errorinfo)////上面的代码实现了从ftp服务器下载文件的功能
{
try
{
filePath = filePath.Replace("我的电脑\\", "");
String onlyFileName = Path.GetFileName(fileName);
string newFileName = filePath + onlyFileName;
if (File.Exists(newFileName))
{
errorinfo = string.Format("本地文件{0}已存在,无法下载", newFileName);
return false;
}
ftpfilepath = ftpfilepath.Replace("\\", "/");
string url = "ftp://" + ftpfilepath;
Connect(url);//连接

reqFTP.Credentials = new NetworkCredential(ftpUserID, 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();
errorinfo = "";
return true;
}
catch (Exception ex)
{
errorinfo = string.Format("因{0},无法下载", ex.Message);
return false;
}
}
#endregion
#region 删除文件
public void DeleteFileName(string fileName)
{
try
{
FileInfo fileInf = new FileInfo(fileName);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
// 默认为true,连接不会被关闭
// 在一个命令之后被执行
reqFTP.KeepAlive = false;
// 指定执行什么命令
reqFTP.Method = WebRequestMethods.Ftp.DeleteFile;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
//MessageBox.Show(ex.Message, "删除错误");
}
}
#endregion
#region 在ftp上创建目录
public void MakeDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.MakeDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
#endregion
#region 删除ftp上目录
public void delDir(string dirName)
{
try
{
string uri = "ftp://" + ftpServerIP + "/" + dirName;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.RemoveDirectory;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
response.Close();
}
catch (Exception ex)
{
}
}
#endregion
#region 获得ftp上文件大小
public long GetFileSize(string filename)
{
long fileSize = 0;
filename = filename.Replace("\\", "/");
try
{
// FileInfo fileInf = new FileInfo(filename);

//string uri1 = "ftp://" + ftpServerIP + "/" + fileInf.Name;
// string uri = filename;
string uri = "ftp://" + filename;
Connect(uri);//连接
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上文件改名
public void Rename(string currentFilename, string newFilename)
{
try
{
FileInfo fileInf = new FileInfo(currentFilename);
string uri = "ftp://" + ftpServerIP + "/" + fileInf.Name;
Connect(uri);//连接
reqFTP.Method = WebRequestMethods.Ftp.Rename;
reqFTP.RenameTo = newFilename;
FtpWebResponse response = (FtpWebResponse)reqFTP.GetResponse();
//Stream ftpStream = response.GetResponseStream();
//ftpStream.Close();
response.Close();
}
catch (Exception ex)
{
// MessageBox.Show(ex.Message);
}
}
#endregion
#region 获得文件明晰
public string[] GetFilesDetailList()
{
return GetFileList("ftp://" + ftpServerIP + "/", WebRequestMethods.Ftp.ListDirectoryDetails);
}
public string[] GetFilesDetailList(string path)
{
path = path.Replace("\\", "/");
return GetFileList("ftp://" + path, WebRequestMethods.Ftp.ListDirectoryDetails);
}
#endregion
}
}

FTP上传类的更多相关文章

  1. FTP上传-封装工具类

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

  2. 高可用的Spring FTP上传下载工具类(已解决上传过程常见问题)

    前言 最近在项目中需要和ftp服务器进行交互,在网上找了一下关于ftp上传下载的工具类,大致有两种. 第一种是单例模式的类. 第二种是另外定义一个Service,直接通过Service来实现ftp的上 ...

  3. ftp上传或下载文件工具类

    FtpTransferUtil.java工具类,向ftp上传或下载文件: package utils; import java.io.File; import java.io.FileOutputSt ...

  4. ftp上传下载工具类

    package com.taotao.utils; import java.io.File; import java.io.FileInputStream; import java.io.FileNo ...

  5. FTP上传文件到服务器

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

  6. 再看ftp上传文件

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

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

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

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

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

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

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

随机推荐

  1. Apache kafka原理与特性(0.8V)

    前言: kafka是一个轻量级的/分布式的/具备replication能力的日志采集组件,通常被集成到应用系统中,收集"用户行为日志"等,并可以使用各种消费终端(consumer) ...

  2. django上传下载大文件

    上传 def upFile(file): upload_dir = '/tmp/upload/%s' % username if request.method == 'POST': upload_fi ...

  3. contenteditable

    http://www.w3school.com.cn/tags/att_global_contenteditable.asp 做编辑器经常用这个属性 使得整个编辑区域所见所得 http://www.c ...

  4. node.js npm权限问题try running this command again as root/Administrator.

    npm install报错; try running this command again as root/Administrator. 以管理员身份打开cmd 开始菜单->所有程序->附 ...

  5. Cocoapods注意点

    1 安装和升级$ sudo gem install cocoapods $ pod setup 2 更换为taobao的源 $ gem sources -r https://rubygems.org/ ...

  6. m球求n盒子问题

    球同盒同可空盒问题 #include <bits/stdc++.h> using namespace std; const int N = 25; int dp[N][N]; int ma ...

  7. JS,CSS,HTML制作网页首页,视频轮播,隐藏点击等等。

    在整个项目中,总共写了1000+的代码,可以更加简单优化的.整个主页交互效果能基本,包括轮播,视频,点击变化形状,移入蒙版,瀑布流加载滑动,旋转等等.轮播导航没有完全做完,暂时做了往右无限推动.个人觉 ...

  8. ASP.NET的一般处理程序对图片文件的基本操作

    以一个小项目为例: 验证码: public class VerifyCodeHelper { public VerifyCodeHelper() { this.ran = new Random(); ...

  9. JQuery权限管理

    <title></title> <script src="JS/jquery-1.7.1.js"></script> <scr ...

  10. Python学习总结11:获取当前运行类名和函数名

    一. 使用内置方法和修饰器方法获取类名.函数名 1. 外部获取 从外部的情况好获取,可以使用指向函数的对象,然后用__name__属性. def a(): pass a.__name__ 或者 get ...